参考: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: 15217742393@163.com 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 = "15217742393@163.com"; 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"; } }