简介
在日常的开发中,在Java项目中调用邮件服务,进行邮件的发送的场景是比较常见的,本篇将介绍Java中邮件的相关使用
发送邮件配置类
发送邮件,肯定是需要相关的邮件服务配置,我们将其进行一个封装
@Data
@Builder
public class EmailConfig {
private String host;
private String port;
private String user;
private String password;
}
如上所示,常用的配置是主机路径、端口、用户名和密码,这些东西基本上在项目中是一个通用的配置,自行获取
邮件发送服务
下面是目前常用的一个通用封装,感觉应该是能覆盖目前大部分的使用场景
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.SneakyThrows;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
public class EmailService {
private final EmailConfig config;
private final Session session;
@SneakyThrows
public EmailWarnService(final EmailWarnConfig emailSendConfig) {
config = emailSendConfig;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", config.getHost());
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", config.getPort());
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(config.getUser(),
config.getPassword());
}
});
}
@SneakyThrows
public void sendsMessage(String receiveAddress, String title, String message, Map<String, String> attachments) {
try {
Message mailMessage = new MimeMessage(session);
Address from = new InternetAddress(config.getUser());
mailMessage.setFrom(from);
String[] recipientList = receiveAddress.split(",");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String recipient : recipientList) {
recipientAddress[counter] = new InternetAddress(recipient.trim());
counter++;
}
mailMessage.setRecipients(Message.RecipientType.TO, recipientAddress);
mailMessage.setSubject(title);
mailMessage.setSentDate(Calendar.getInstance().getTime());
Multipart multiPart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(message, "text/html; charset=utf-8");
multiPart.addBodyPart(bodyPart);
for (String fileName: attachments.keySet()) {
byte[] bytes = attachments.get(fileName).getBytes(StandardCharsets.UTF_8);
ByteArrayDataSource barrds = new ByteArrayDataSource(bytes, "application/octet-stream");
bodyPart = new MimeBodyPart();
bodyPart.setDataHandler(new DataHandler(barrds));
bodyPart.setFileName(MimeUtility.encodeText(fileName));
multiPart.addBodyPart(bodyPart);
}
mailMessage.setContent(multiPart);
Transport.send(mailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
如上所示,在构造函数中进行了连接相关的初始化,后面基本上是复用这个session,目前使用下来基本正常
下面的发送函数是一个通用的,可以发送给多个邮箱和附件
附件可能需要比较少,但有的话,还是挺关键的,这里使用一个map结构,key是文件名,value是附件内容,使其能进行多个附件的发送
在使用过程中需要注意大小,避免一些数据量比较大的操作
邮件发送的使用
目前使用下来的最佳实践还是将邮件模板保存到数据库中,使用时进行加载,然后替换其中的占位符之类的比较方便
如下,我们定义了一个邮件模板:
【xxx邮件】xxxx <br><br>时间:%s <br><br> %s。(具体查看附件)
其中我们将时间和正文内容设置为占位符,后面的使用,对应的进行填充即可
参考链接
|