1、首先导入所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、配置yml文件
spring:
mail:
host: smtp.163.com
username: 邮箱名
password: 授权码
port: 25
也可以是其他邮箱
spring:
mail:
host: smtp.qq.com
username: 邮箱名
password: 授权码
port: 587
3、授权码获取(以qq和163为例)
qq邮箱:
下滑找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,点击开启,根据提示发送短信即可获取
163邮箱:
点击:POP3/SMTP/IMAP,点击开启,根据提示发送短信即可获取
4、主要代码如下
package com.coding.mail.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
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.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
@Slf4j
@Api(tags = "发送邮件")
@RequiredArgsConstructor
@RestController
public class EmailController {
private final JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String account;
@ApiOperation("多人群发简单邮件")
@PostMapping("sendSimpleMail")
public String sendSimpleMail(
@ApiParam("收件地址") @RequestParam String address,
@ApiParam("标题") @RequestParam String subject,
@ApiParam("正文") @RequestParam String body) {
SimpleMailMessage smm = new SimpleMailMessage();
smm.setFrom(account);
// 设置多个收件人
smm.setTo(address.split(","));
smm.setSubject(subject);
smm.setText(body);
javaMailSender.send(smm);
return "发送成功";
}
@ApiOperation("发送带附件的邮件")
@PostMapping("sendAttachmentMail")
public String sendAttachmentMail(
@ApiParam("收件地址") @RequestParam String address,
@ApiParam("标题") @RequestParam String subject,
@ApiParam("正文") @RequestParam String body,
@ApiParam("附件") @RequestPart MultipartFile file) throws MessagingException, IOException {
//定制复杂邮件信息MimeMessage
MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
//使用MimeMessageHelper帮助类,并设置multipart多部件使用为true
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom(account);
mimeMessageHelper.setTo(new String[]{address});
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(body);
String fileName= file.getOriginalFilename();
mimeMessageHelper.addAttachment(fileName, file);
log.info("fileName:{}", fileName);
javaMailSender.send(mimeMailMessage);
return "发送成功";
}
}