android javamail获取邮件太多太慢_Spring Boot 发送邮件实战全解析

9d40bea6a3d795f17444394671fd0470.gif

1.前言

欢迎阅读 Spring Boot 2 实战系列[1] 电子邮件虽然近几年有点“退火”,但是在开发中依然有举足轻重的地位。在比较正式的场合我们依然通过电子邮件来传递信息和回执。今天我们就来学一下如何在 Spring Boot 下发送电子邮件。

2. 依赖

Java 发送邮件依赖 jakarta 项目(原 javaEE)提供的 jakarta.mail 组件, Maven 坐标:

   <dependency>
<groupId>com.sun.mailgroupId>
<artifactId>jakarta.mailartifactId>
<version>1.6.4version>
<scope>compilescope>
dependency>

Spring 官方 又将其进行进一步封装成开箱即用的 spring-boot-starter-mail 项目:

 <dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
dependency>

在 Spring Boot 项目中我们引入上面的 spring-boot-starter-mail 依赖即可为你的项目集成邮件功能。接下来我们来对邮件功能进行参数配置。

3. 邮箱配置

spring-boot-starter-mail 的配置由 MailProperties 配置类提供。在 application.yml 配置文件中以 spring.mail 为前缀。我们来看看都有哪些配置项。

#  字符集编码 默认 UTF-8
spring.mail.default-encoding=UTF-8
# SMTP 服务器 host qq邮箱的为 smtp.qq.com 端口 465 587
spring.mail.host=smtp.qq.com
# SMTP 服务器端口 不同的服务商不一样
spring.mail.port=465
# SMTP 服务器使用的协议
spring.mail.protocol=smtp
# SMTP服务器需要身份验证 所以 要配置用户密码

# 发送端的用户邮箱名
spring.mail.username=business@felord.cn
# 发送端的密码 注意保密
spring.mail.password=oooooxxxxxxxx
# 指定mail会话的jndi名称 优先级较高 一般我们不使用该方式
spring.mail.jndi-name=
# 这个比较重要 针对不同的SMTP服务器 都有自己的一些特色配置该属性 提供了这些配置的 key value 封装方案 例如 Gmail SMTP 服务器超时配置 spring.mail.properties.mail.smtp.timeout= 5000
spring.mail.properties. =
# 指定是否在启动时测试邮件服务器连接,默认为false
spring.mail.test-connection=false

针对不同的邮箱有不同的配置,所以我们介绍几种我们常用的邮箱配置,可以直接拿来配置。

但是请注意很多邮箱需要手动开启 SMTP 功能,请务必确保该功能打开。如果在公有云上部署请避免使用 25 端口。

3.1 QQ 邮箱

# 需要开启 smtp
spring.mail.host=smtp.qq.com
spring.mail.port=465
# 发件人的邮箱
spring.mail.username=master@felord.cn
# qq 邮箱的第三方授权码 并非个人密码
spring.mail.password=qztgbzfftdwdbjcddff
#开启ssl 否则 503 错误
spring.mail.properties.mail.smtp.ssl.enable=true

获取授权码的方式参见下图点击生成授权码:

8905bfe434781485642011390e377c7a.png

3.2 163 信箱

# 需要在设置中开启 smtp
spring.mail.host=smtp.163.com
spring.mail.port=465
# 发件人的邮箱
spring.mail.username=youraccount@163.com
# 邮箱的授权码 并非个人密码
spring.mail.password=qztgbzfftdwdbjcddff
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.imap.ssl.socketFactory.fallback=false
spring.mail.properties.mail.smtp.ssl.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

3.3 阿里云信箱 (参考QQ邮箱配置)


3.4 gmail

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=youraccount@gmail.com
# 安全建议使用应用程序密码代替Gmail密码。参见相关文档
spring.mail.password=yourpassword

# 个性配置
spring.mail.properties.mail.debug=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true

# SSL, post 465
#spring.mail.properties.mail.smtp.socketFactory.port = 465
#spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory

3.5 outlook

spring.mail.host=smtp-mail.outlook.com
spring.mail.port=587
spring.mail.username=youraccount@outlook.com
spring.mail.password=yourpassword

spring.mail.properties.mail.protocol=smtp
spring.mail.properties.mail.tls=true

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com

4. 邮件发送服务

配置完毕后我们就可以构建我们自己的邮件发送服务了。

4.1 纯文本邮件

最简单的就是发送纯文本邮件了,完整代码如下:

package cn.felord.mail.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
* The Email service.
*
* @author felord.cn
* @since 2020 /1/14 23:22
*/
@Component
public class EmailService {
@Resource
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;


/**
* 发送纯文本邮件.
*
* @param to 目标email 地址
* @param subject 邮件主题
* @param text 纯文本内容
*/
public void sendMail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();

message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}

4.2 带附件的邮件

有时候我们需要在邮件中携带附件。我们就需要发送 Mime 信息了,代码如下:

    /**
* 发送邮件并携带附件.
* 请注意 from 、 to 邮件服务器是否限制邮件大小
*
* @param to 目标email 地址
* @param subject 邮件主题
* @param text 纯文本内容
* @param filePath 附件的路径 当然你可以改写传入文件
*/
public void sendMailWithAttachment(String to, String subject, String text, String filePath) throws MessagingException {

File attachment = new File(filePath);
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
helper.addAttachment(attachment.getName(),attachment);
javaMailSender.send(mimeMessage);

}

这里需要注意的是 fromto 邮件服务器是否限制邮件大小,避免邮件超出限定大小。

4.3 富文本邮件

现在很多的场景是通过电子邮件发送宣传营销的富文本,甚至图文并茂带链接。所以这个功能非常实用。可以通过前端编写适配邮件的 html 模板。将数据动态化注入模板即可。我们先来写一个 html :

<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8">
<title>title>
head>
<body>
<h2>你好,朋友h2>
<div>
<p>欢迎关注公众号:<strong>Felordcnstrong>p>
<p>同时也欢迎访问: <a href="https://felord.cn">felord.cna>p>
<p><img src="cid:qr" alt="">p>
div>
body>
html>

上面大致上跟我们平时的 html 基本一致,区别在于如果有内嵌的图片元素比如 img 标签 ,其 src 中需要使用占位符,规则为 cid:后紧接着一个你自己定义的标记。比如 qr 。后面会在代码中体现这个 qr。如果使用占位符则必须指定 否则图片无法显示!当然你也可以直接把图片的 url 链接写入模板,就像下面:

<html lang="en">
<body>
<h2>你好,朋友h2>
<div>
<p>欢迎关注公众号:<strong>Felordcnstrong>p>
<p>同时也欢迎访问: <a href="https://felord.cn">felord.cna>p>
<p><img src="https://ae01.alicdn.com/kf/H29f220acefaa49469b5507ef296085abk.png" alt="">p>
div>
body>
html>

然后我们编写 Java 代码,实际逻辑是 4.2 章节 的加强,如下:

    /**
* 发送富文本邮件.
*
* @param to 目标email 地址
* @param subject 邮件主题
* @param text 纯文本内容
* @param filePath 附件的路径 当然你可以改写传入文件
*/
public void sendRichMail(String to, String subject, String text, String filePath) throws MessagingException {

MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);

helper.setText(text,true);
// 图片占位写法 如果图片链接写入模板 注释下面这一行
helper.addInline("qr",new FileSystemResource(filePath));
javaMailSender.send(mimeMessage);

}

如果你采用类似上面第二个 HTML 模板,图片逻辑就不需要了,注释掉 helper.addInline() 方法即可。

5. 总结

今天我们对 Spring Boot 发送邮件进行了细致的归纳,对常用的邮箱配置进行了列举。同时对发送各种类型的邮件也进行了实现以及细节上的探讨。希望能对你有所帮助。多多关注,更多干货尽在 felord.cn[2]

参考资料

[1]

Spring Boot 2 实战系列: https://felord.cn/categories/spring-boot/

[2]

felord.cn: https://felord.cn

beb5d5e7165c0b5536709b7279fdd931.png

3e026ef30609d7f60e1bf6180d143182.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值