1、引入依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
</dependency>
2、配置
spring.mail.host=smtp.163.com
spring.mail.port=25
spring.mail.username=xxxx@163.com #发件人邮箱地址
spring.mail.password=xxxxxxxxxxxx #发件人邮箱客户端密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enabled=true
3、邮箱代码
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
@Slf4j
@Service
@Setter
@Getter
public class MailHelperService {
@Value("${spring.mail.host: }")
private String host;// SMTP服务器地址
@Value("${spring.mail.port: }")
private String port;// 端口
@Value("${spring.mail.username: }")
private String username;// 登录SMTP服务器的用户名
@Value("${spring.mail.password: }")
private String password;// 登录SMTP服务器的密码
@Value("${spring.mail.properties.mail.smtp.auth: }")
private String auth;//使用AUTH命令对用户进行身份验证
@Value("${spring.mail.properties.mail.smtp.ssl.enabled: }")
private String sslEnabled;//使用SSL连接并使用SSL端口
private List<String> recipients = new ArrayList<String>(); // 收件人地址集合
private String subject; // 邮件主题
private String content; // 邮件正文
private List<String> attachmentNames = new ArrayList<String>(); // 附件路径信息集合
//发邮件,收件人接受多人
public void sendMail() {
log.info(">>>>>>>>>>>>>>>>>>>邮件发送开始>>>>>>>>>>>>>>");
//1、连接邮件服务器的参数配置
Properties properties = new Properties();
//设置发件人的SMTP服务器地址
properties.put("mail.smtp.host", host);
//设置发件人的SMTP服务器端口
properties.put("mail.smtp.port", port);
//设置用户的认证方式
properties.put("mail.smtp.auth", auth);
//设置用户的认证方式
properties.put("mail.smtp.ssl.enable", sslEnabled);
//2、创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getInstance(properties);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
try {
// 发件人
Address address = new InternetAddress(username);
message.setFrom(address);
// 创建邮件的接收者地址,并设置到邮件消息中
Address[] tos = null;
recipients.add(username); // 收件人,添加发件人邮箱地址,不添加spring会认为邮件是垃圾邮件,发送失败
if (recipients.size() > 0) {
// 为每个邮件接收者创建一个地址
tos = new InternetAddress[recipients.size()];
for (int i = 0; i < recipients.size(); i++) {
tos[i] = new InternetAddress(recipients.get(i));
}
} else {
return;
}
// 将所有接收者地址都添加到邮件接收者属性中
message.setRecipients(Message.RecipientType.TO, tos);
message.setRecipients(Message.RecipientType.BCC, tos);
// 主题
message.setSubject(changeEncode(subject));
// 时间
message.setSentDate(new Date());
//邮件中含有附件,那邮件的中必须定义multipart/mixed类型,邮件通过multipart/mixed类型中定义的boundary标识将附件内容同邮件其它内容分成不同的段
Multipart multipart = new MimeMultipart();
// 添加文本
BodyPart text = new MimeBodyPart();
text.setText(content);
multipart.addBodyPart(text);
String strFileName;
// 添加附件
for (String fileName : attachmentNames) {
BodyPart adjunct = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(fileName);
adjunct.setDataHandler(new DataHandler(fileDataSource));
strFileName = changeEncode(fileDataSource.getName());
adjunct.setFileName(strFileName);
multipart.addBodyPart(adjunct);
}
// 清空收件人集合,附件集合
recipients.clear();
attachmentNames.clear();
message.setContent(multipart);
message.saveChanges();
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>邮件发送失败,属性设置异常>>>>>>>>>>>>>>", e);
return;
}
try {
//4、根据session对象获取邮件传输对象Transport
Transport transport = session.getTransport("smtp");
//设置发件人的账户名和密码
log.info(">>>>>>>>>>>>>>>>>>>开始connect邮箱服务器>>>>>>>>>>>>>>");
transport.connect(host, username, password);
//发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
//5、关闭邮件连接
transport.close();
log.info(">>>>>>>>>>>>>>>>>>>邮件发送结束>>>>>>>>>>>>>>");
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>邮件发送失败:原因Transport>>>>>>>>>>>>>>", e);
}
}
/**
* 进行base64加密,防止中文乱码
*/
public String changeEncode(String str) {
try {
System.setProperty("mail.mime.splitlongparameters", "false");
String charset = "UTF-8";
String a1 = "";
if (str.equals(new String(str.getBytes(charset), charset))) {
a1 = new String(str.getBytes(charset), "UTF-8");
} else if (str.equals(new String(str.getBytes("GBK"), charset))) {
a1 = new String(str.getBytes("GBK"), charset);
} else {
a1 = new String(str.getBytes(), charset);
}
str = MimeUtility.encodeText(a1, charset, "B"); // "B"代表Base64
} catch (UnsupportedEncodingException e) {
log.error(">>>>>>>>>>>>>>>>>>>邮件主题进行base64加密异常>>>>>>>>>>>>>>", e);
}
return str;
}
}
4、调用
/**
* 发送邮件
*
* @param recipients 收件人
* @param subject 主题
* @param content 内容
* @param attachmentNames 附件
* @return
*/
private void sendMail(List<String> recipients, String subject, String content, List<String> attachmentNames) {
mailHelperService.setAttachmentNames(attachmentNames);
mailHelperService.setContent(content);
mailHelperService.setSubject(subject);
mailHelperService.setRecipients(recipients);
//发送邮件功能
mailHelperService.sendMail();
}