1. 获取授权码
- 以126邮箱为例,点开设置,选择POP3/SMTP/IMAP
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6b9ee31d2ceb9fda4c4d4751501846cd.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/29d3814d4f801864ba0dca4eac340cae.png)
- 扫码二维码,发送要求的短信内容到指定的号码即可,然后会返回授权密码
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a8450ae09b38c63c486e17ca63eb531f.png)
2. jar包引入
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
3. 配置application
# 默认编码
spring.mail.default-encoding=utf-8
# 邮件服务器的地址
spring.mail.host=smtp.126.com
# 用户的账号
spring.mail.username=111@126.com
# 授权密码
spring.mail.password=xxx
# 邮件服务器的端口
spring.mail.port=465
# SSL 连接配置
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.ssl.required=true
# 开启debug,查看邮件发送日志
spring.mail.properties.mail.debug=true
# 邮件接收者
mail.userlist=123@qq.com,456@qq.com
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fdd3f91f62b9b0df57f351d2e713775e.png)
4. 代码实现
import java.io.File;
import java.util.Date;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
public class EmailController {
@Value("${spring.mail.username}")
private String mailUsername;
@Value("${mail.userlist}")
private String mailUserList;
@Resource
private JavaMailSender javaMailSender;
@GetMapping("/simpleMsg")
public void simpleMsg() {
SimpleMailMessage simpMsg = new SimpleMailMessage();
simpMsg.setFrom(mailUsername);
simpMsg.setTo(mailUserList.split(","));
simpMsg.setSubject("Hello world!");
simpMsg.setText("哈哈哈\n哈哈哈");
simpMsg.setSentDate(new Date());
javaMailSender.send(simpMsg);
}
@GetMapping("htmlMsg")
public void htmlMsg() throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(mailUsername);
helper.setTo(mailUserList.split(","));
helper.setSubject("Hello world!");
helper.setText("<h1>哈哈哈h1</h1>\n哈哈哈", true);
helper.setSentDate(new Date());
File file = new File("/Users/xxx/Downloads/cceda5ad-df31-4610-9b63-ed0503561934.jpg");
helper.addAttachment(file.getName(), file);
javaMailSender.send(message);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/929ce1344c575fafcbdbc95fd4474fc7.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4b7f06c7f2b9352624fb049fd79d754a.png)