天天看點

Apache Commons Email郵件發送

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();