使用Apache commons-mail实现电子邮件发送
以Maven工程为例:
1.在pom.xml文件中引用commons-mail组件包
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
2.在properties文件中配置邮件基本信息(后期便于维护,如有变动不动代码直接改配置文件即可)
//邮件服务器地址
mail.server.host=smtp.ourfuture.cn
//端口:默认25
mail.smpt.port=25
//收件人地址
mail.from=zhangsan@ourfuture.cn
//收件人密码
mail.from.password=*************
3.编写邮件发送工具类
/**
* 邮件工具类
* @author Administrator
* 使用JavaMail进行邮件发送
*
*/
@Service
public class MailUtils {
private static Logger logger = LoggerFactory.getLogger(MailUtils.class);
@Autowired
private PropertyUtils prop; //properties文件读取工具
public void send(MailEntity mailEntity) {
try {
//获取邮箱相关信息(邮件服务器地址、邮件smtp端口,发送者,发送者密码)
String host = prop.getValue("mail.server.host").get();
String port = prop.getValue("mail.smpt.port").get();
String username = prop.getValue("mail.from").get();
String pwd = prop.getValue("mail.from.password").get();
//实例化邮件
HtmlEmail htmlEmail = new HtmlEmail();
//设置邮箱服务器信息
htmlEmail.setHostName(host);
//设置smtp端口号(各邮件服务器可能存在smtp端口不相同问题)
htmlEmail.setSmtpPort(Integer.parseInt(port));
//设置邮箱发送者
htmlEmail.setFrom(username);
//设置密码验证器
htmlEmail.setAuthentication(username, pwd);
//设置邮件编码
htmlEmail.setCharset("UTF-8");
//设置邮件主题
htmlEmail.setSubject(mailEntity.getSubject());
//设置邮件内容
htmlEmail.setMsg(mailEntity.getContent());
//添加附件
List<EmailAttachment> emailAttachments = mailEntity.getAttachments();
if(null != emailAttachments && emailAttachments.size() > 0) {
for (EmailAttachment emailAttachment : emailAttachments) {
htmlEmail.attach(emailAttachment);
}
}
//收件人
List<String> toAddress = mailEntity.getToAddress();
if(null != toAddress && toAddress.size() > 0) {
for (String to : toAddress) {
htmlEmail.addTo(to);
}
}
//抄送人
List<String> ccAddress = mailEntity.getCcAddress();
if(null != ccAddress && ccAddress.size() > 0) {
for (String cc : ccAddress) {
htmlEmail.addCc(cc);
}
}
//密送人
List<String> bccAddress = mailEntity.getBccAddress();
if(null != bccAddress && bccAddress.size() > 0) {
for (String bcc : bccAddress) {
htmlEmail.addBcc(bcc);
}
}
//邮件发送
htmlEmail.send();
logger.info("send email success!!!");
} catch (EmailException e) {
logger.error("email throw exception!");
e.printStackTrace();
}
}
3.工程中封装邮箱信息(发件人信息动态获取),调用工具类发送邮件信息
//创建邮件对象
MailEntity mailEntity = new MailEntity();
//邮件标题
mailEntity.setSubject(monitorEvent.getTitle());
//邮件内容
mailEntity.setContent(DateUtils.format(monitorEvent.getStarttime())+" <br/>"+monitorEvent.getResourceName()+"<br/>"+monitorEvent.getDescription());
//邮件接收者
List<String> toAddress = Lists.newArrayList();
for (XUser xuser : userLists) {
if(StringUtils.isNotBlank(xuser.getEmail())) {
toAddress.add(xuser.getEmail());
}
}
mailEntity.setToAddress(toAddress);
//邮件发送
MailUtils mailUtils = new MailUtils();
mailUtils.send(mailEntity);
logger.info("mail send success!!!");