首页 > 代码库 > spring boot发送邮件

spring boot发送邮件

1.引入maven依赖包

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-mail</artifactId></dependency>

2.配置文件

#JavaMailSender 邮件发送的配置#spring.mail.host=smtp.qq.comspring.mail.host=smtp.163.comspring.mail.username=username@163.comspring.mail.password=shouquanmaspring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required=true

不去邮箱配置授权码的话会报错:

javax.mail.AuthenticationFailedException: 550 User has no permission出错
邮箱开启pop3/smtp等协议,然后用授权码代替密码来模拟登陆就可以发送成功了!

3.发送简洁邮件

public class MysteryController {

  @Autowired
  private JavaMailSender javaMailSender;

  @Value("${spring.mail.username}")

  private String username;

// 发送邮件@RequestMapping("/sendMail")public Map sendMail() {    SimpleMailMessage message = new SimpleMailMessage();    message.setFrom(username);    message.setTo("xxx@qq.com");    message.setSubject("标题:测试标题");    message.setText("测试内容部份");    javaMailSender.send(message);    Map result = new HashMap();    result.put("发送成功", "success");    return result;  }
}

4.发送HTML格式的邮件

@RequestMapping("/sendMail")
public
void sendMail() { MimeMessage message = null; try { message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(username); helper.setTo("xxx@qq.com"); helper.setSubject("标题:发送Html内容"); StringBuffer sb = new StringBuffer(); sb.append("<h1>大标题-h1</h1>") .append("<p style=‘color:#F00‘>红色字</p>") .append("<p style=‘text-align:right‘>右对齐</p>"); helper.setText(sb.toString(), true); } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(message);}

这里创建的是MimeMessageHelper,且在调用setText时需要在第二个参数传入true,这样才会使用HTML格式发送邮件

ps:将helper.setFrom(username);修改成helper.setFrom(new InternetAddress(username, "咸鱼", "UTF-8"));这样收件方就可以看到自己的名称。

spring boot发送邮件