Spring Boot demo系列(七):邮件服务

Stella981
• 阅读 513

2021.2.24 更新

1 概述

Spring Boot整合邮件服务,包括发送普通的文本邮件以及带附件的邮件。

2 邮箱选择

这里选择的是QQ邮箱作为发送的邮箱,当然也可以选择其他的邮箱,只是具体的配置不一样。

使用QQ邮箱的话,需要在个人设置中开启SMTP服务:

Spring Boot demo系列(七):邮件服务

Spring Boot demo系列(七):邮件服务

发送短信后完成验证即可,会有一个授权码,先复制下来保存。

3 具体实现

3.1 依赖

提供了starter

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

gradle

implementation 'org.springframework.boot:spring-boot-starter-mail'

3.2 邮件接口

只有两个简单的接口,一个是发送纯文本的,一个是发送带附件的:

public interface MailService {
    void sendSimpleMail(String to,String subject,String content);
    void sendAttachmentMail(String to, String subject, String content, Path file) throws MessagingException;
}

3.3 接口实现

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MailServiceImpl implements MailService{
    private final JavaMailSender sender;

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

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        sender.send(message);
    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, Path file) throws MessagingException {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content);
        helper.addAttachment(file.getFileName().toString(),new FileSystemResource(file));
        sender.send(message);
    }
}

JavaMailSenderSpring Boot携带的邮件发送接口,注入后可以发送SimpleMailMessage以及MimeMessage类型的信息。

  • SimpleMailMessage:简单的邮件信息对象,封装了一些常见的属性,比如寄信地址以及收信地址,发送日期,主题,内容等
  • MimeMessage:发送MIME类型的邮件信息,MIME指的是Multipurpose Internet Mail Extensiosns,是描述消息内容类型的因特网标准,能包含文本,图像,音频,视频以及其他应用程序专用的数据
  • MimeMessageHelper:用于设置MimeMessage属性的类,可以利用其中的addAttachment添加附件
  • setFrom/setTo/setSubject/setText:分别表示设置寄信地址/收信地址/主题/内容

3.4 测试类

@SpringBootTest
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
class DemoApplicationTests {
    private final MailService service;

    @Test
    void contextLoads() throws URISyntaxException, MessagingException {
        service.sendSimpleMail("xxx@xxx.com","这是主题","这是内容");
        service.sendAttachmentMail("xxxx@xx.com","这是主题","这是内容", Path.of(Objects.requireNonNull(getClass().getClassLoader().getResource("pic/1.jpg")).toURI()));
        //附件为resources下pic/1.jpg
        service.sendAttachmentMail("xxxx@xxx.com","这是主题","这是内容", Path.of("/","srv","http","1.jpg"));
        //附件为/srv/http/1.jpg
    }

发送文本直接指定主题和内容即可,发送带附件的话:

  • 如果是resources下的内容,使用getClass().getClassLoader().getReource("xxx/xxx")
  • 如果是绝对路径,使用Path.of("/","path1","path2",...,"filename")

3.5 配置文件

spring:
  mail:
    host: smtp.qq.com
    username: xxxxxxx@qq.com
    password: xxxxxxxxxx
    port: 465
    properties:
      mail:
        smtp:
          ssl:
            enable: true
          auth: true
          starttls:
            enable: true
            required: true

作为Demo使用只需要修改username以及password即可。

  • username:发送的用户邮箱
  • password:不是邮箱密码,而是授权码,就是刚才开启SMTP服务出现的授权码

其他配置说明:

  • hostSMTP服务器地址
  • port:端口,可以选择465/587host以及port可以参考QQ邮箱文档
  • properties:里面都是一些安全设置,开启SSL以及认证等

3.6 测试

修改测试类的邮箱,运行单元测试即可。

Spring Boot demo系列(七):邮件服务

如果没通过,可以参考这里,罗列了常见的错误码以及可能的解决方案。

4 加密

由于用户名以及密码都直接写在了配置文件中,如果泄露的话会很危险,因此需要对配置文件进行加密。

具体的话可以参考笔者之前的原力计划文章,戳这里

4.1 依赖

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

gradle

implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.3")

4.2 配置文件

配置文件只需要加上加密口令即可:

jasypt:
  encryptor:
    password: test

默认使用的是PBE加密算法,PBE其实是一种组合加密算法,默认是采用HCMA算法(混合CMA-ES算法)+SHA512消息摘要算法+AES256对称加密算法。

另外,如果不想在配置文件直接写上加密的口令,可以使用以下三种方法对口令进行参数化:

命令行参数(运行时设置):

java -jar xxx.jar --jasypt.encryptor.password=test

应用环境变量(运行时设置):

java -Djasypt.encryptor.password=test -jar xxx.jar

系统环境变量(在配置文件中设置):

jasypt:
  encryptor:
    password: ${TEST}
# 表示获取环境变量TEST的值作为加密口令

4.3 测试类

新建一个测试类:

@SpringBootTest
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class EncryptAndDecrypt {
    private final StringEncryptor encryptor;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    @Test
    public void encrypt()
    {
        System.out.println(encryptor.encrypt(username));
        System.out.println(encryptor.encrypt(password));
    }

    @Test
    public void decrypt()
    {
        System.out.println(username);
        System.out.println(password);
    }
}

4.4 获取密文

假设明文如下:

Spring Boot demo系列(七):邮件服务

运行encrypt即可,输出如下:

Spring Boot demo系列(七):邮件服务

4.5 替换明文

加上前缀ENC(以及后缀)去替换明文:

Spring Boot demo系列(七):邮件服务

4.6 测试

获取明文直接运行decrypt即可,输出:

Spring Boot demo系列(七):邮件服务

这样就完成加密了。

5 源码

Java版:

Kotlin版:

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
菜鸟阿都 菜鸟阿都
2年前
python实现邮件发送
前言使用python的第三方库yagmail实现邮件发送的功能yagmail官网文档:第一步:申请一个邮箱作为发送邮箱此处以网易邮箱为例,因为使用python代码实现邮件的发送,需要开启邮箱的授权密码功能,用生成的授权密码作为发送邮件的密码,以下步骤为开启网易邮箱的授权密码功能。第二步:安装yagmail库languagepipinstally
Irene181 Irene181
2年前
最全总结!聊聊 Python 发送邮件的几种方式
1\.前言邮件,作为最正式规范的沟通方式,在日常办公过程中经常被用到我们都知道Python内置了对SMTP的支持,可以发送纯文本、富文本、HTML等格式的邮件本文将聊聊利用 Python发送邮件的3种方式2\.准备以126邮箱为例,在编码之前,我们需要开启SMTP服务然后,手动新增一个授权码其中,账号、授权码和服务器地址用于连接登录
Irene181 Irene181
2年前
最全总结!聊聊 Python 发送邮件的几种方式
1\.前言邮件,作为最正式规范的沟通方式,在日常办公过程中经常被用到我们都知道Python内置了对SMTP的支持,可以发送纯文本、富文本、HTML等格式的邮件本文将聊聊利用 Python发送邮件的3种方式2\.准备以126邮箱为例,在编码之前,我们需要开启SMTP服务然后,手动新增一个授权码其中,账号、授权码和服务器地址用于连接登录
Wesley13 Wesley13
2年前
javamail发送邮件(简单邮件qq邮箱)
/\\<dependency<groupIdcom.sun.mail</groupId<artifactIdjavax.mail</artifactId<version1.5.4</version</dependency\//\上面是maven需要添加的依赖\/p
Stella981 Stella981
2年前
MediaWiki 设置QQ邮箱SMTP(SSl方式)发送邮件
MediaWiki默认采用本机作为邮件发送服务器,而发出去的邮件很容易被接收方当成垃圾邮件或者直接被屏蔽掉,所以建议直接采用第三方smtp服务器,以腾讯企业邮箱为例:安装需要的库PHP7使用composer安装依赖库composerrequireupdatenodevpear/mailpear/net_smt
Wesley13 Wesley13
2年前
4cast
4castpackageloadcsv.KumarAwanish发布:2020122117:43:04.501348作者:KumarAwanish作者邮箱:awanish00@gmail.com首页:
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
2年前
Jenkins设置运行结果自动发送邮箱通知
Jenkins设置运行结果自动发送邮箱通知1获取邮箱授权码登录邮箱选择“设置”开启IMAP/SMTP服务开启后需要通过手机发送短信到线上获取授权码!(https://img2018.cnblogs.com/blog/1798505/201909/1798505201909280544535181522354728.png)例如我
把帆帆喂饱 把帆帆喂饱
1年前
Springboot整合Redis实现邮箱验证码
Springboot整合Redis实现邮箱验证码开启邮箱服务打开https://mail.qq.com/登录你自己的qq账号选择账户点击开启STMP服务:发送短信:发送完,点击我已发送,然后得到密码:Springboot配置邮箱pom依赖xmlorg.sp