(仿牛客社区项目)Java开发笔记2.1:测试发送邮件功能

发送邮件

由于项目的注册功能需要向注册用户发送激活邮件,先完成Spring Email邮件功能的测试。

1.邮箱设置

需要启用客户端SMTP服务。

2.Spring Email

2.1导入jar依赖包

在pom.xml添加如下依赖。

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
			<version>2.1.5.RELEASE</version>
</dependency>

2.2在配置文件中对邮箱参数进行配置

application.properties添加与spring发送邮件相关的配置。值得注意的是,不同邮件系统所需的配置不同。【网易邮箱和新浪邮箱properties配置不同,网易邮箱需要授权码。】

# MailProperties gmail和163邮箱配置不一致,需要注意
spring.mail.host=smtp.163.com
#spring.mail.port=465
spring.mail.username=xxxxxxx@163.com
spring.mail.password=xxxxxxxxxxxxx
#spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#spring.mail.properties.mail.smtp.ssl.enable=tr

3.测试邮件功能

在test包中创建MailTests测试类,代码如下。

package com.gerrard.community;

import com.gerrard.community.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 = CommunityApplication.class)
public class MailTests {

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    //直接发送文字信息
    @Test 
    public void testTextMail() {
        mailClient.sendMail("xxxxx@qq.com", "TEST", "Welcome.");
    }

    //发送动态网页
    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username", "sunday");  //将变量内容填充到模板中

        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("xxxxxx@qq.com", "HTML", content);
    }

}

Thymeleaf 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>

4.功能演示

1.先测试发送文本邮件功能,运行testTextMail方法,目标邮箱成功收到了来自spring.mail.host端发送的测试文本邮件。

InkedNowCoder_2_1

2.在测试结合Thymeleaf发送HTML邮件,运行testHtmlMail方法,目标邮箱也成功收到了来自spring.mail.host端发送的测试HTML邮件。

InkedNowCoder_2_2

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值