pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
发送简单文本邮件
@Autowired
JavaMailSenderImpl mailSender;
@Async
public void SendEmail(){
// 发送简单邮件
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// 邮件主题
simpleMailMessage.setSubject("主题");
// 邮件内容
simpleMailMessage.setText("正文");
// 发送给谁
simpleMailMessage.setTo("1233@");
// 从哪里来
simpleMailMessage.setFrom("11111@");
mailSender.send(simpleMailMessage);
}
// 启动类开启异步注解功能,及时给前台返回结果
@EnableAsync
发送带附件的邮件
public void SendEmail() throws MessagingException {
// 一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
// 组装内容
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,"utf-8");
helper.setSubject("你好");
helper.setText("<a>正文<a>",true);
// 附件
helper.addAttachment("1.jpg", new File("C:\\Users\\yh\\Desktop\\20210425165104.png"));
helper.addAttachment("2.jpg", new File("C:\\Users\\yh\\Desktop\\20210425165207.png"));
helper.setTo("1234@");
helper.setFrom("11111@");
mailSender.send(mimeMessage);
}
yml
spring:
mail:
username: 11111@
password: 开启smtp服务获取密码
host: smtp.
#不同邮件后缀 host不同
注意开启服务