Maven包依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置application.yml
spring:
#邮箱
mail:
host: smtp.qq.com
username: 2269472297@qq.com
#QQ邮箱的授权码
password: yztfquoomtrvebgd
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
接着写一个工具类
@Component
public class MailConfig
{
@Autowired
private JavaMailSenderImpl mailSender;
@Value("${spring.mail.username}")
private String username;
/**
* 发送纯文本形式的email
*
* @param toEmail
* 收件人邮箱
* @param title
* 邮件标题
* @param content
* 邮件内容
*/
public void sendTextMail(String toEmail, String title, String content)
{
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(username);
msg.setTo(toEmail);
msg.setSubject(title);
msg.setText(content);
mailSender.send(msg);
}
/**
* 发送带有html的内容
*
* @param userId
* @throws MessagingException
*/
public void sendHtmlMail(String toEmail, String title, String htmlContent) throws MessagingException
{
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
helper.setFrom(username);
helper.setTo(toEmail);
helper.setSubject(title);
helper.setText(htmlContent, true);
mailSender.send(msg);
}
/**
* 添加附件的email发送
*
* @param toEmail
* 收件人地址
* @param title
* 邮件标题
* @param content
* 文本内容
* @param aboutFiles
* 附件信息 每个子项都是一个文件相关信息的map Map<String,String>: 1.filePath 2.fileName
* @throws Exception
* 异常
*/
public void sendAttachmentMail(String toEmail, String title, String content, List<Map<String, String>> aboutFiles)
throws Exception
{
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
helper.setFrom(username);
helper.setTo(toEmail);
helper.setSubject(title);
helper.setText(content);
FileSystemResource resource = null;
for (Map<String, String> file : aboutFiles)
{
resource = new FileSystemResource(file.get("filePath"));
if (resource.exists())
{// 是否存在资源
File attachmentFile = resource.getFile();
helper.addAttachment(file.get("fileName"), attachmentFile);
}
}
mailSender.send(msg);
}
}
测试
@Controller
public class IndexController
{
@Autowired
private MailConfig mailConfig;
@RequestMapping("/text")
public void text()
{
mailConfig.sendTextMail("xxxx@qq.com", "测试", "hahaha");
}
}