使用Commons Email发送邮件以及与Spring的结合

使用Maven构建项目,在pom.xml中添加依赖包,


    ...
    
        org.apache.commons
        commons-email
        1.3.3
    

参考User guide,基于QQ邮箱发送文本邮件,

public static void main(String[] args) {
    Email email = new SimpleEmail();
    // 连接参数配置
    email.setHostName("smtp.qq.com");
    email.setSmtpPort(465);
    email.setAuthenticator(new DefaultAuthenticator("QQ No", "QQ Password");
    email.setSSLOnConnect(true);
    // 邮件相关内容
    try {
        email.setFrom("[email protected]");
        email.setMsg("Hello, world!");
        email.addTo("[email protected]");
        email.send();
    } catch (EmailException e) {

    }
}

与使用JDBC连接数据库一样,前面的代码包含大量的模板操作,所以结合Spring,与JdbcTemplate类似,构建MailTemplate。在applicationContext-mail.xml中声明Bean,


    
        
            
                classpath:mail.properties
            
        
    

    
        
        
        
        
            
                
                
            
        
    

    
        
    

将连接参数添加到mail.properties,me.voler.jechat.core.MailTemplate即构建的MailTemplate,

package me.voler.jechat.core;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class MailTemplate {

    private SimpleEmail simpleMail;

    public void send(String msg, String to) {
        this.send("【邮件】", msg, to);
    }

    /**
     * 
     * @param subject 邮件主题
     * @param msg 邮件正文
     * @param toList 收件人列表
     */
    public void send(String subject, String msg, String... toList) {

        try {
            simpleMail.setSubject(subject);
            simpleMail.setMsg(msg);
            simpleMail.addTo(toList);

            simpleMail.setSSLOnConnect(true);
            simpleMail.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }

    }

    public SimpleEmail getSimpleMail() {
        return simpleMail;
    }

    public void setSimpleMail(SimpleEmail simpleMail) {
        this.simpleMail = simpleMail;
    }

}

使用构建的MailTemplate发送文本邮件,

@Autowired
@Qualifier("mailTemplate")
private MailTemplate mailTemplate;

public void sendEmptyMail() {
    mailTemplate.send("中文测试,English Test.", "[email protected]");
}

SimpleEmail的父类的属性sslOnConnect的set方法名为setSSLOnConnect,如果直接在applicationContext-mail.xml的simpleMail Bean下配置会提示Bean property is not writable or has an invalid setter method

你可能感兴趣的:(使用Commons Email发送邮件以及与Spring的结合)