当前位置: 首页 > 工具软件 > Commons Email > 使用案例 >

Apache Commons Email邮件发送

郎思远
2023-12-01

1、Commons Email将javamail封装了,方便使用。只需要引入以下pom.xml

 <!-- mail -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.4</version>
        </dependency>

2、发送简单的文本

    SimpleEmail email = new SimpleEmail();
    email.setHostName("xxxx.com");
    email.setAuthentication("xxx.com", "***");//邮件服务器验证:用户名/密码
    email.setCharset("UTF-8");// 必须放在前面,否则乱码
    email.addTo("xxx.com");//收件人
    email.setFrom("xxx.com", "xxx");
    email.setSubject("subject中文");
    email.addCc("抄送人邮箱");
    email.setMsg("msg中文");
    email.send();

3、发送带附件的邮件

    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("xxx.com");
    email.setAuthentication("xxx.com", "***");
    email.setCharset("UTF-8");
    email.addTo("xxxl.com");
    email.setFrom("xxx.com", "support");
    email.setSubject("subject中文");
    email.setMsg("msg中文");
    
    EmailAttachment attachment = new EmailAttachment();
    attachment.setPath("d:/a.gif");// 本地文件
    // attachment.setURL(new URL("http://xxx/a.gif"));//远程文件
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    attachment.setDescription("abc");
    attachment.setName("abc");
    
    email.attach(attachment);
    email.send();

4、发送HTML格式邮件

    HtmlEmail email = new HtmlEmail();
    email.setHostName("xxx.com");
    email.setAuthentication("xxx.com", "***");
    email.setCharset("UTF-8");
    email.addTo("xxx.com");
    email.setFrom("xxx.com", "support");
    email.setSubject("标题");
    email.setHtmlMsg("<b>测试内容</b>");
    email.send();

5、偌需要通过代理来发送邮件

    SimpleEmail email = new SimpleEmail();
    email.setHostName("xxxx.com");
    email.setAuthentication("xxx.com", "***");//邮件服务器验证:用户名/密码
    email.setCharset("UTF-8");// 必须放在前面,否则乱码
    email.addTo("xxx.com");//收件人
    email.setFrom("xxx.com", "xxx");
    email.setSubject("subject中文");
    email.addCc("抄送人邮箱");
    email.setMsg("msg中文");
    Properties properties = System.getProperties();
    properties.setProperty("socksProxyHost",代理服务器的地址);
    properties.setProperty("socksProxyPort",代理服务器的端口号);
    email.send();





 类似资料: