SpringBoot 整合JavaMailSender发送邮件

简介: SpringBoot 整合JavaMailSender发送邮件

一、创建项目,引入依赖

我们使用IEDA创建项目,在选择依赖页面,注意选择mail

之后,IDE会自动下载对应的依赖。

二、配置项目,初步运行

创建配置文件 src/main/resources/application.yml

配置内容为

  • 项目端口号,为了不和本地其他项目冲突
  • mail相关账号配置
server:
  port: 8200
  servlet:
    encoding:
      charset: UTF-8
      force: true
spring:
  mail:
    host: smtp.xxx
    username: xxx
    password: xxx
    default-encoding: UTF-8
    # 配置 SSL 加密工厂
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          debug: true

其中mail配置有三个值

host: smtp.xxx
username: xxx
password: xxx

分别对应你的stmp服务器的地址,和对应的用户名密码。

我们可以简单粗暴地理解为JavaMailSender使用我们的账户密码来发送邮件。

三、stmp服务器配置

我们目前使用的大部分邮箱都支持stmp服务配置,拿QQ邮箱来说,进入设置页面,选择账户,就能看到自己的stmp服务启用状态。

点击链接之后,我们能看到完整的smtp服务说明。

如果您的邮件客户端不在上述列出的范围内,您可以尝试如下通用配置:

**接收邮件服务器:**imap.qq.com

**发送邮件服务器:**smtp.qq.com

**账户名:**您的QQ邮箱账户名(如果您是VIP邮箱,账户名需要填写完整的邮件地址)

**密码:**您的QQ邮箱密码

**电子邮件地址:**您的QQ邮箱的完整邮件地址

如何设置IMAP服务的SSL加密方式?

使用SSL的通用配置如下:

**接收邮件服务器:**imap.qq.com,使用SSL,端口号993

**发送邮件服务器:**smtp.qq.com,使用SSL,端口号465或587

**账户名:**您的QQ邮箱账户名(如果您是VIP帐号或Foxmail帐号,账户名需要填写完整的邮件地址)

**密码:**您的QQ邮箱密码

**电子邮件地址:**您的QQ邮箱的完整邮件地址

IMAP服务目前有什么功能限制?

目前IMAP暂时还不支持删除文件夹和重命名文件夹的操作(后续版本中会支持)。

如果你使用的是QQ邮箱,按上面配置会返回

javax.mail.AuthenticationFailedException: 535 Login Fail. Please enter your authorization code to login. More information in http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

腾讯的文档会告诉我们,第三方登录客户端,需要用到授权码。

授权码是QQ邮箱推出的,用于登录第三方客户端的专用密码。
适用于登录以下服务:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

点击这里,开始生成授权码。

短信发送完成之后,点击我已发送,我们就能得到一个授权码。

之后,我们把授权码填写到配置文件的password中。

再次尝试,发送成功!

四、案例

1. 发送文字内容

@GetMapping("/send")
    public void Send(){
        // 发邮件逻辑
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper;
        String text = "我是正文";
        String subject = "标题";
        String to = "xx@qq.com"; //目标地址
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSentDate(new Date());
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(text);
//            if (attachmentContent != null) {
//                mimeMessageHelper.addAttachment(MimeUtility.encodeWord(attachmentFilename), new ByteArrayResource(attachmentContent));
//            }
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            System.out.print("发送邮件失败");
        }
        System.out.print("测试");
    }

2. 发送附件

发送附件需要调用addAttachment()方法,源码在/.m2/repository/org/springframework/spring-context-support/5.3.13/spring-context-support-5.3.13.jar!/org/springframework/mail/javamail/MimeMessageHelper.class

public void addAttachment(String attachmentFilename, File file) throws MessagingException {
        Assert.notNull(file, "File must not be null");
        FileDataSource dataSource = new FileDataSource(file);
        dataSource.setFileTypeMap(this.getFileTypeMap());
        this.addAttachment(attachmentFilename, (DataSource)dataSource);
    }
    public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) throws MessagingException {
        String contentType = this.getFileTypeMap().getContentType(attachmentFilename);
        this.addAttachment(attachmentFilename, inputStreamSource, contentType);
    }
    public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource, String contentType) throws MessagingException {
        Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
        if (inputStreamSource instanceof Resource && ((Resource)inputStreamSource).isOpen()) {
            throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
        } else {
            DataSource dataSource = this.createDataSource(inputStreamSource, contentType, attachmentFilename);
            this.addAttachment(attachmentFilename, dataSource);
        }
    }
Resource resource = resourceLoader.getResource("classpath:attachment/exp.html");
mimeMessageHelper.addAttachment("exp.html",  resource);

发送成功!

3. 原文内插入图片

addInline()源码如下

public void addInline(String contentId, File file) throws MessagingException {
        Assert.notNull(file, "File must not be null");
        FileDataSource dataSource = new FileDataSource(file);
        dataSource.setFileTypeMap(this.getFileTypeMap());
        this.addInline(contentId, (DataSource)dataSource);
    }
    public void addInline(String contentId, Resource resource) throws MessagingException {
        Assert.notNull(resource, "Resource must not be null");
        String contentType = this.getFileTypeMap().getContentType(resource.getFilename());
        this.addInline(contentId, resource, contentType);
    }
    public void addInline(String contentId, InputStreamSource inputStreamSource, String contentType) throws MessagingException {
        Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
        if (inputStreamSource instanceof Resource && ((Resource)inputStreamSource).isOpen()) {
            throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
        } else {
            DataSource dataSource = this.createDataSource(inputStreamSource, contentType, "inline");
            this.addInline(contentId, dataSource);
        }
    }

具体用法如下

mimeMessageHelper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
Resource resource2 = resourceLoader.getResource("classpath:attachment/att.png");
mimeMessageHelper.addInline("identifier1234", resource2);

插入成功!


相关文章
|
3月前
|
安全 JavaScript Java
SpringBoot实现定时发送邮件
SpringBoot实现定时发送邮件
51 0
|
3月前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
102 0
|
3月前
SpringBoot+Mybatis-Plus+PageHelper分页+多条件查询
SpringBoot+Mybatis-Plus+PageHelper分页+多条件查询
77 0
|
2月前
|
运维 Java 关系型数据库
Spring运维之boot项目bean属性的绑定读取与校验
Spring运维之boot项目bean属性的绑定读取与校验
37 2
|
2月前
|
存储 运维 Java
Spring运维之boot项目开发关键之日志操作以及用文件记录日志
Spring运维之boot项目开发关键之日志操作以及用文件记录日志
40 2
|
2月前
|
Java Maven
springboot项目打jar包后,如何部署到服务器
springboot项目打jar包后,如何部署到服务器
145 1
|
2月前
|
XML 运维 Java
Spring运维之boot项目打包jar和插件运行并且设置启动时临时属性和自定义配置文件
Spring运维之boot项目打包jar和插件运行并且设置启动时临时属性和自定义配置文件
33 1
|
2月前
springboot2.4.5使用pagehelper分页插件
springboot2.4.5使用pagehelper分页插件
43 0
|
2月前
|
缓存 运维 Java
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
27 0
|
3月前
|
Java Spring
Spring boot项目如何发送邮件
Spring boot项目如何发送邮件
34 2