Spring boot 中发送邮件
Posted baizhuang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot 中发送邮件相关的知识,希望对你有一定的参考价值。
参考:https://blog.csdn.net/qq_39241443/article/details/81293939
添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
添加配置:邮箱不同配置不同
spring: mail: host: smtp.163.com username: [email protected] password: 授权码 default-encoding: UTF-8
发送简单文本:
package com.wct.send; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; @Component public class SendTextMail @Autowired private JavaMailSender mailSender; @Value("$spring.mail.username") private String from; public void sendTextMail(String to,String subject,String content) throws Exception SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); mailSender.send(message);
发送html :
package com.wct.send; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; @Component public class SendHtmlMail @Autowired private JavaMailSender mailSender; @Value("$spring.mail.username") private String from; public void sendHtmlMail(String to,String subject,String content) throws Exception MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper send = new MimeMessageHelper(message,true); send.setFrom(from); send.setTo(to); send.setSubject(subject); send.setText(content,true); mailSender.send(message);
测试类:
package com.wct.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.wct.send.SendHtmlMail; import com.wct.send.SendTextMail; @RestController public class SendController @Autowired private SendTextMail sendTextMail; @Autowired private SendHtmlMail sendHtmlMail; private static String TO = "[email protected]"; private static String SUBJECT = "主题文件"; private static String CONTENT = "this is a mail !"; private static String Html = "<a href=\"www.baidu.com\">超链接!</a>"; @GetMapping("/sendText") public String send01() throws Exception sendTextMail.sendTextMail(TO,SUBJECT,CONTENT); return "success"; @GetMapping("/sendHtml") public String send02() throws Exception sendHtmlMail.sendHtmlMail(TO,SUBJECT,Html); return "success";
以上是关于Spring boot 中发送邮件的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot中使用JavaMailSender发送邮件