项目-3-发送邮件

本文介绍了如何在SpringBoot项目中配置SMTP服务发送邮件,包括邮箱设置、导入相关依赖、配置邮件参数,并展示了如何使用JavaMailSender发送普通邮件。此外,还详细讲解了结合Thymeleaf模板引擎发送HTML邮件的过程,包括创建模板和使用TemplateEngine处理模板内容。

项目-3-发送邮件

1. 发送邮件

  • 邮箱设置
    • 启用客户端SMTP服务
  • Spring Email
    • 导入 jar 包
    • 邮箱参数配置
    • 使用 JavaMailSender 发送邮件
  • 模板引擎
    • 使用 Thymeleaf 发送 HTML 邮件

1.1 邮箱设置

  • 启用客户端SMTP服务

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1cB6E4qI-1623408263329)(/Users/apple/Desktop/屏幕快照 2021-03-09 上午9.13.10.png)]

在开启SMTP时,会有一个授权码:********

在邮箱参数配置中,授权码即为密码

1.2 Spring Email

  • 导入 jar 包
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>sping-boot-start-mail</artifactId>
    <version>2.1.5.RELEASE</version>
</dependency>
  • 邮箱参数配置
# MailProperties
#MailProperties
spring.mail.host=smtp.sina.com
#邮箱端口一般默认465
spring.mail.port=465
spring.mail.username=@sina.com
spring.mail.password=****
#协议
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
1.3 使用 JavaMailSender 发送邮件

为了方便代码的复用,建立一个工具包util,写一个工具类MailClient。

package com.guo.util;

//为方便邮件的发送,建立发送邮件的工具类

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);

    //引入JavaMailSender
    @Autowired
    private JavaMailSender javaMailSender;

    //设置邮件发送方,因为这个地址是固定的,因此可以从配置文件中取出
    @Value("${spring.mail.username}")
    private String from;

    //发送邮件的方法

    /**
     *
     * @param to 收件方的邮箱
     * @param subject 邮件的主题
     * @param context 邮件的内容
     */
    public void sendMail(String to, String subject, String context){
        try {
            //查看JavaMailSender源码,发现需要创建MimeMessage
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //同时可以利用MimeMessageHelper对mimeMessage补充,设置邮件的具体信息
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            //设置邮件的具体信息
            helper.setFrom(from); //发件人
            helper.setTo(to); //收件人
            helper.setSubject(subject); //主题
            helper.setText(context,true); //true:允许html文本
            //发送邮件
            javaMailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("邮件发送失败"+e.getMessage());
        }
    }
}

测试:

package com.guo;

import com.guo.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = ForumApplication.class)
public class MailTests {
    //邮件测试类
    @Autowired
    private MailClient mailClient;
    @Test
    public void test01(){
        //发送普通邮件
        mailClient.sendMail("**@qq.com","mail测试","测试成功");
    }
}
1.4 模板引擎
  • 使用 Thymeleaf 发送 HTML 邮件

在Templete/email中创建demo.html

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

测试

package com.guo;

import com.guo.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = ForumApplication.class)
public class MailTests {
    //邮件测试类
    @Autowired
    private MailClient mailClient;

    @Test
    public void test01(){
        //发送普通邮件
        mailClient.sendMail("1**@qq.com","mail测试","测试成功");
    }
    
    //利用模板引擎发送HTML邮件,需要导入spring配置的TemplateEngine
    @Autowired
    private TemplateEngine templateEngine;
    
    @Test
    public void test02(){
        //利用模板引擎发送HTML邮件时,需要利用thymeleaf的context设置内容
        Context context = new Context();
        //设置变量信息
        context.setVariable("username","thymeleaf");
        //利用模板引擎保存邮件内容
        String process = templateEngine.process("/mail/demo", context);
        mailClient.sendMail("**@qq.com","html测试", process);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值