SpringBoot-Mail发送邮件
------------恢复内容开始------------
1.pom文件添加mail相关的starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2. application.properties文件或者application.yaml文件中配置邮箱
#mail spring.mail.default-encoding=utf-8 spring.mail.host=smtp.sina.com spring.mail.port=465 spring.mail.protocol=smtps spring.mail.username=mailtest788@sina.com spring.mail.password=授权码
3. MailClient 邮件代理类
package wht.spring.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; @Component public class MailClient { private static final Logger logger= LoggerFactory.getLogger(MailClient.class); @Autowired JavaMailSender mailSender; //发送邮件的类,SpringBoot自动构造该类对象并注入 @Value("${spring.mail.username}") String from; public void sendMail(String to,String subject,String context){ try{ //消息类,表示邮件内容 MimeMessage message=mailSender.createMimeMessage(); //MimeMessageHelper辅助消息类设置邮件内容 MimeMessageHelper helper=new MimeMessageHelper(message); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); //true表示发送的内容是html格式 helper.setText(context,true); mailSender.send(helper.getMimeMessage()); } catch (MessagingException e) { logger.error("发送邮件失败"+e.getMessage()); } } }
4. 发送邮件测试
package wht.spring; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import wht.spring.utils.MailClient; @SpringBootTest public class MailTest { @Autowired MailClient mailClient; @Test public void mailTest(){ String to="1099472434@qq.com"; String subject="mailTest"; String context="你好Nils"; mailClient.sendMail(to,subject,context); } }
5. 模板引擎制作邮件内容
package wht.spring; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import wht.spring.utils.MailClient; @SpringBootTest public class MailTest { @Autowired MailClient mailClient; @Autowired TemplateEngine templateEngine; //thymeleaf starter中的类,springboot自动创建该类对象并注入 @Test public void testHtmlMail() { //thymeleaf依赖中的Context类,作用相当于Controller返回的Model,用于渲染模板 Context context = new Context(); context.setVariable("username", "sunday"); String content = templateEngine.process("/mail/demo", context); System.out.println(content); mailClient.sendMail("lihonghe@nowcoder.com", "HTML", content); } }
------------恢复内容结束------------