Java Web 项目学习(二) 发送邮件

邮箱设置:启用客户端SMTP服务

  开启邮箱中的POP3/SMTP服务
  

 Spring Email

  • 导入jar包:mvnrepository.com  搜 spring mail。在pom.xml中添加 Spring Boot Starter Mail 依赖。
  • 邮箱参数配置:(application.properties)
    #MailProperties
    #声明访问的域名
    spring.mail.host=smtp.sina.com
    spring.mail.port=465
    spring.mail.username=邮箱地址
    spring.mail.password=密码(开启服务后的授权码,并非是自己设的密码)
    #加s表示用的是安全的协议
    spring.mail.protocol=smtps
    #在发送邮件的时候采用ssl安全连接的
    spring.mail.properties.mail.smtp.ssl.enable=true

    报错:org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 
    解决方法:
      1.检查自己的邮箱是否开启pop3/smtp服务。
           2.检查程序中所填的邮箱密码是否为开启pop3/smtp服务时所给的授权码。不是自己定义的密码!!!
           3.检查授权码是否己经被重置更改。授权码开启后,pop,imap,smtp验证都使用授权码进行验证。在客户端不可再使用登录密码进行验证。已登录的客户端需要重新输入授权码验证。

  • 使用javaMailSender发送邮件:
    封装发送邮件的整个过程,写一个工具。新建util包,包下新建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());
            }
        }
    
    }
    View Code

 模板引擎

  • 使用Thymeleaf发送HTML邮件

    针对发送动态的HTML文件,需要建立模板。在resources下的mail包下建立demo.html

    <!DOCTYPE html>
    <html lang="en" xmlns="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>邮件示例</title>
    </head>
    <body>
        <p>欢迎你,<span style="color: indigo" th:text="${username}"></span>!</p>
    </body>
    </html>

    在测试类MailTests中添加: (展开的代码都很重要!!!!是核心代码!!!!!!记住!!!!)

        @Autowired
        private TemplateEngine templateEngine;
    
        @Test
        public void testHtmlMail(){
            //MVC情况下,在controller中,只需要返回模板路径,dispatchServlet就会自动的调用
            //这里,主动的调用thymleaf的模板引擎,他有一个核心类,也是被spring容器管理起来的。需要的话直接注入
            Context context = new Context();
            context.setVariable("username","sunday");
            //调用模板引擎生成动态网页,并不能发邮件,还是要有发邮件的步骤
            String content = templateEngine.process("mail/demo",context);
            System.out.println(content);
    
            //发邮件
            mailClient.sendMail("752488291@qq.com","HtmlTest",content);
    
        }
原文地址:https://www.cnblogs.com/codinghard/p/14815067.html