首页 > 编程语言 > 详细

利用spring发送邮件

时间:2021-07-28 18:19:47      阅读:7      评论:0      收藏:0      [点我收藏+]

1、打开邮箱的POP3/SMTP服务,以sina邮箱为例

技术分享图片

 

 

 

2、在porm.xml中加入如下依赖,修改properties

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
#MailProperties
spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=###
spring.mail.password=###
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true

3、MailClient代码

@Component
public class MailClient {

private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

@Autowired
private JavaMailSender mailSender;

@Value("${spring.mail.username}")
private String from;

public void sendMail(String to,String subject,String content){
try {
MimeMessage message=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败:"+e.getMessage());
}
}

}

4、发送邮件

private MailClient mailClient;
mailClient.sendMail("xxx@qq.com","TESTMYHERO","HIHIHIHI");

5、HTML邮件

public void testHtmlMail(){
Context context=new Context();
context.setVariable("username","sunday");

String content=templateEngine.process("/mail/demo",context);
System.out.println(content);
mailClient.sendMail("xxx@qq.com","HTMLTEST",content);

}

demo.html
<p>欢迎你,<span style="color:red" th:text="${username}"></span></p>

利用spring发送邮件

原文:https://www.cnblogs.com/xuetianyu/p/15070979.html

(0)
(0)
   
举报
评论 一句话评论(0
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!