GreenMail是开源的邮件服务测试套件
在POM中定义项目依赖:
<!--实现发送必须的类库-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>com.icegreen</groupId>
<artifactId>greenmail</artifactId>
<version>1.3.1b</version>
</dependency>
在测试代码中的片段
try{
//msg对应将要发送的邮件
MimeMessage msg=javaMailSender.createMimeMessage();
//msgHelp帮助设置邮件信息
MimeMessageHelper msgHelp=new MimeMessageHelper(msg);
//设置发件人、收件人和邮件主题
msgHelp.setFrom(systemEmail);
msgHelp.setTo(to);
msgHelp.setSubject(subject);
//true表示邮件内容为html格式
msgHelp.setText(htmlText,true);
javaMailSender.send(msg);
}catch (Exception e){
e.printStackTrace();
}
将邮件服务器的相关配置分离到外部的properties中,
email.protocol=smtp
email.host=smtp.163.com
email.port=465
email.username=your_id@163.com
email.password=your_password
email.auth=zsfeng
email.systemEmail=your-id@qq.com
对GreenMail的使用:
在执行测试任务之前,要启动邮件服务器:
private GreenMail greenMail;
@Before
public void startMailService(){
greenMail=new GreenMail(ServerSetup.SMTP);
greenMail.setUser("your_id@163.com","your_password");
greenMail.start();
}
在测试完成之后,要关闭GreenMail:
@After
public void stopMailService(){
greenMail.stop();
}
测试环境设置的properties不同:
email.protocol=smtp
email.host=localhost
email.port=25
email.username=your_id@163.com
email.password=your_password
email.auth=zsfeng
email.systemEmail=your-id@qq.com