1、引入发送邮件依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
2、邮件发送工具类
参数说明:
smtpHost :邮箱服务器,如 smtp.qq.com
password :授权码
fromMail :发件人邮箱
toMail :收件人邮箱
title :邮件标题
content :邮件内容
File Path :附件路径
@Component
public class MailPublish {
private static void send(String smtpHost, String password, String fromMail, String toMail, String title, String content, String filePath) throws Exception {
Properties props = new Properties();
props. setProperty ("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", smtpHost);
props.setProperty("mail.smtp.auth", "true");
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromMail, password);
}
};
Session session = Session. getInstance (props, auth);
Message message = new Mime Message(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toMail));
message.setSubject(title);
// 邮件正文
MimeBodyPart body = new MimeBodyPart();
body.setContent(content, "text/html; charset =utf-8");
// 准备附件
DataSource source = new FileDataSource(new File(filePath));
DataHandler handler = new DataHandler(source);
// 添加附件
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(handler);
attachment.setFileName(MimeUtility.encodeText(handler.getName()));
// 将正文和附件放入multipart
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachment);
message.setContent(multipart);
// 发送邮件
Transport.send(message);
}
如果您有什么好的想法与方法,欢迎在评论区留言,我们一起讨论~