添加自动装配
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
申请授权码
配置参数
#配置smtp服务主机地址
spring.mail.host=smtp.qq.com
#发送者邮箱
spring.mail.username=979279164@qq.com
#配置密码,注意不是真正的密码,而是刚刚申请到的授权码
spring.mail.password=ajzydmsdyptvbdgb
#默认的邮件编码为UTF-8
spring.mail.default-encoding=UTF-8
工具类
package com.tianqiauto.base.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @author wjx
* @description 邮件发送工具类
*/
@Component
public class MailSendUtils implements ApplicationContextAware {
private static String from;
private static JavaMailSender mailSender;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
mailSender = (JavaMailSender) applicationContext.getBean("mailSender");
from = PropertiesUtils.getDBPropertiesByName("spring.mail.username");
}
/**
* @description 发送普通纯文本邮件
* @param to 收信人
* @param subject 主题
* @param content 内容
*/
public static void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);//收信人
message.setSubject(subject);//主题
message.setText(content);//内容
message.setFrom(from);//发信人
mailSender.send(message);
}
/**
* @description 发送HTML邮件,可携带附件
* @param to 收信人
* @param subject 主题
* @param content 内容
* @param filePaths 路径信息
* @exception MessagingException 发送失败抛出异常
*/
public static void sendAttachmentMail(String to, String subject, String content, String... filePaths) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
//true代表支持多组件,如附件,图片等
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file;
for (String filePath : filePaths) {
file = new FileSystemResource(new File(filePath));
//添加附件,可多次调用该方法添加多个附件
helper.addAttachment(file.getFilename(), file);
}
mailSender.send(message);
}
}