1.pom加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
2.配置文件
spring:
mail:
host: smtp.qq.com # qq邮箱smtp.qq.com 163邮箱:smtp.163.com
username: xxxxxxxxx@qq.com # 发送账号
password: xxxxxxxxxx # 邮箱授权码: 从qq邮箱网页版——账户——开启POP3/SMTP服务,然后获取授权码
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
starttls:
enable: false
required: false
方式一
3.代码发送
@RestController
@RequestMapping("/email")
public class EmailController {
@Value("${spring.mail.username}")
private String username;
@Autowired
JavaMailSender javaMailSender;
@GetMapping("/send")
public void search() {
SimpleMailMessage simpMsg = new SimpleMailMessage();
simpMsg.setFrom(username); //发送者
simpMsg.setTo("xxx@qq.com"); //接收者
simpMsg.setSubject("邮件主题");
simpMsg.setText("邮件内容啊啊啊啊");
javaMailSender.send(simpMsg);
}
}
方式二 MimeMessage
异步调用
ExecutorService executorService = Executors.newSingleThreadExecutor();
//要有这个,不然multipartFiles为空
RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
executorService.submit(() -> {
commonService.emailWithPreview(email, customerName, content, companyName, multipartFiles);
});
@Override
public Result<Void> emailWithPreview(EmailSendDto emailSendDto, MultipartFile[] multipartFiles) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
//发件人
if (emailSendDto.getSenderName() != null && !emailSendDto.getSenderName().isEmpty()) {
mimeMessage.setFrom(new InternetAddress(userName, emailSendDto.getSenderName(), "UTF-8"));
} else {
mimeMessage.setFrom(userName);
}
//收件人
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailSendDto.getEmail()));
//主题
mimeMessage.setSubject(emailSendDto.getSubject());
//正文内容(含文本和内嵌图片)
MimeMultipart multipart = new MimeMultipart();
multipart.setSubType("mixed");//有附件必须是mixed
for (MultipartFile attachment : multipartFiles) {
//MultipartFile转成图片
File pdfFile = multipartFile2File(attachment, "/home/");
File imgFile = pdf2png(pdfFile, "jpg").get(0);
//准备图片数据
MimeBodyPart imageBodyPart = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(imgFile.getPath()));
imageBodyPart.setDataHandler(dh);//在我们的body中放入这个处理的图片数据
imageBodyPart.setContentID("bz.jpg");//给图片设置一个ID方便调用
//准备文本数据
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(emailSendDto.getContent() + "<img src='cid:bz.jpg'>", "text/html;charset=UTF-8");
//准备附件
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.setDataHandler(new DataHandler(new FileDataSource(pdfFile.getPath())));
attachmentBodyPart.setFileName(pdfFile.getName());
//拼接图片和文本
MimeMultipart imageAndTextMultipart = new MimeMultipart();
imageAndTextMultipart.addBodyPart(imageBodyPart);
imageAndTextMultipart.addBodyPart(textBodyPart);
imageAndTextMultipart.setSubType("related");//文本和图片内嵌成功
//将拼接好的图片文本再次设置成单独的bodyPart
MimeBodyPart contentBodyPart = new MimeBodyPart();
contentBodyPart.setContent(imageAndTextMultipart);
//拼接附件和图片文本
multipart.addBodyPart(attachmentBodyPart);//附件
multipart.addBodyPart(contentBodyPart);//文字和图片的结合
}
//保存到message中
mimeMessage.setContent(multipart);
//保存并发送
mimeMessage.saveChanges();
mailSender.send(mimeMessage);
return Result.ofSucceed();
} catch (Exception e) {
log.error("邮件发送失败: {}", e.getMessage());
throw new BusinessException(CommonServiceCodeEnum.EMAIL_SEND_FAILURE);
}
}
方式三 MimeMessageHelper
@Resource
private JavaMailSender mailSender;
@Override
public Result<Void> sendEmailWithAttachment(EmailSendDto emailSendDto, MultipartFile[] multipartFiles) {
log.info("发送邮件,emailSendDto={}", emailSendDto.toString());
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mimeMessage, true);
if (emailSendDto.getSenderName() != null && !emailSendDto.getSenderName().isEmpty()) {
helper.setFrom(new InternetAddress(userName, emailSendDto.getSenderName(), "UTF-8"));
} else {
helper.setFrom(userName);
}
helper.setTo(emailSendDto.getEmail());
helper.setSubject(emailSendDto.getSubject());
helper.setText(emailSendDto.getContent(), true);
//附件
if (multipartFiles.length > 0) {
for (MultipartFile multipartFile : multipartFiles) {
helper.addAttachment(Objects.requireNonNull(multipartFile.getOriginalFilename()), multipartFile);
}
}
mailSender.send(mimeMessage);
return Result.ofSucceed();
} catch (Exception e) {
log.error("邮件发送失败: {}", e.getMessage());
throw new BusinessException(CommonServiceCodeEnum.EMAIL_SEND_FAILURE);
}
}