Spring Boot 发送邮件 JavaMail。

Spring Boot 发送邮件。



使用场景。

  • 注册验证。
  • 网点营销。
  • 安全的最后一道防线。
  • 提醒、监控警告。
  • 触发机制。


邮件发送的原理。

邮件传输协议。

SMTP 和 POP3。
IMAP 和 MIME。



邮件发送流程。

在这里插入图片描述



邮件历史。
  • 1969.10.,世界第一封电子邮件。

  • 1987.9.,中国第一封电子邮件。

  • 30 年发展。

  • Java 发送邮件。

  • Spring 发送邮件。



Spring Boot 发送邮件。

在这里插入图片描述



简单文本邮件。

  • jar 包。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.geek</groupId>
    <artifactId>springboot-mail</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mail</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <!--            <exclusions>
                            <exclusion>
                                <groupId>org.junit.vintage</groupId>
                                <artifactId>junit-vintage-engine</artifactId>
                            </exclusion>
                        </exclusions>-->
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  • 配置邮件参数。
spring.mail.host=smtp.qq.com
spring.mail.username=lyfGeek@qq.com
spring.mail.password=(邮箱授权码)
spring.mail.default-encoding=utf-8
  • 封装 SimpleMailMessage。
package com.geek.springbootmail.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.Service;

@Service
public class MailService {

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

    @Autowired
    private JavaMailSender javaMailSender;

    public void sayHello() {
        System.out.println("Hello, World.");
    }

    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(from);

        javaMailSender.send(simpleMailMessage);
    }
}

  • JavaMailSender 进行发送。
package com.geek.springbootmail.service;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
class MailServiceTest {

    @Resource
    private MailService mailService;

    @Test
    void sayHello() {
        mailService.sayHello();
    }

    @Test
    void sendSimpleMail() {
        mailService.sendSimpleMail("lyfGeek56@gmail.com", "Spring Boot Mail Test.", "Hello Spring Boot Mail, ");
    }
}



HTML 邮件。

multipart

adj.多部件的;多元件的;由几部分组成的

package com.geek.springbootmail.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.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class MailService {

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

    @Autowired
    private JavaMailSender javaMailSender;

    public void sayHello() {
        System.out.println("Hello, World.");
    }

    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(from);

        javaMailSender.send(simpleMailMessage);
    }

    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content, true);
        mimeMessageHelper.setFrom(from);
        javaMailSender.send(mimeMessage);
    }
}

  • test。
package com.geek.springbootmail.service;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import javax.mail.MessagingException;

@RunWith(SpringRunner.class)
@SpringBootTest
class MailServiceTest {

    @Resource
    private MailService mailService;

    @Test
    void sayHello() {
        mailService.sayHello();
    }

    @Test
    void sendSimpleMail() {
        mailService.sendSimpleMail("lyfGeek56@gmail.com", "Spring Boot Mail Test.", "Hello Spring Boot Mail, ");
    }

    @Test
    void sendHtmlMail() throws MessagingException {

        String content = "<html>" +
                "<body>" +
                "<h3> hello world, html </h3>" +
                "</body>" +
                "</html>";

        mailService.sendHtmlMail("yflGeek@gmail.com", "Spring Boot Mail (html).", content);
    }
}



附件邮件。

@Service
public class MailService {

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

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendAttachmentMail(String to, String subject, String content, String filePath) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content, true);

        FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
        String filename = fileSystemResource.getFilename();
        mimeMessageHelper.addAttachment(filename, fileSystemResource);
        javaMailSender.send(mimeMessage);
    }
}

  • test。
package com.geek.springbootmail.service;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import javax.mail.MessagingException;

@RunWith(SpringRunner.class)
@SpringBootTest
class MailServiceTest {

    @Resource
    private MailService mailService;

    @Test
    void sayHello() {
        mailService.sayHello();
    }

    @Test
    void sendSimpleMail() {
        mailService.sendSimpleMail("lyfGeek56@gmail.com", "Spring Boot Mail Test.", "Hello Spring Boot Mail, ");
    }

    @Test
    void sendHtmlMail() throws MessagingException {

        String content = "<html>" +
                "<body>" +
                "<h3> hello world, html </h3>" +
                "</body>" +
                "</html>";

        mailService.sendHtmlMail("yflGeek@gmail.com", "Spring Boot Mail (html).", content);
    }

    @Test
    void sendAttachmentMail() throws MessagingException {
        String filePath = "C:\\Users\\geek\\Desktop\\png。\\jdk_jre。.png";
        mailService.sendAttachmentMail("yflGeek@gmail.com", "Spring Boot Mail (Attachment).", "Attachment...", filePath);
    }
}



图片邮件。

package com.geek.springbootmail.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailService {

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

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content, true);

        FileSystemResource fileSystemResource = new FileSystemResource(new File(rscPath));
        mimeMessageHelper.addInline(rscId, fileSystemResource);

        javaMailSender.send(mimeMessage);

    }
}

  • test。
package com.geek.springbootmail.service;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import javax.mail.MessagingException;

@RunWith(SpringRunner.class)
@SpringBootTest
class MailServiceTest {

    @Resource
    private MailService mailService;

    @Test
    void sayHello() {
        mailService.sayHello();
    }

    @Test
    void sendSimpleMail() {
        mailService.sendSimpleMail("lyfGeek56@gmail.com", "Spring Boot Mail Test.", "Hello Spring Boot Mail, ");
    }

    @Test
    void sendHtmlMail() throws MessagingException {

        String content = "<html>" +
                "<body>" +
                "<h3> hello world, html </h3>" +
                "</body>" +
                "</html>";

        mailService.sendHtmlMail("yflGeek@gmail.com", "Spring Boot Mail (html).", content);
    }

    @Test
    void sendAttachmentMail() throws MessagingException {
        String filePath = "C:\\Users\\geek\\Desktop\\png。\\jdk_jre。.png";
        mailService.sendAttachmentMail("yflGeek@gmail.com", "Spring Boot Mail (Attachment).", "Attachment...", filePath);
    }

    @Test
    void sendInlineResourceMail() throws MessagingException {
        String imgPath = "C:\\Users\\geek\\Desktop\\png。\\jdk_jre。.png";
        String rscId = "geek01";
        String content = "<html><body> A mail with images. <img src=\'cid: " - rscId - "\'> </img></body></html>";
        mailService.sendInlineResourceMail("yflGeek@gmail.com", "Spring Boot Mail (image).", content, imgPath, rscId);
    }
}



邮件模板~Thymeleaf。

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
package com.geek.springbootmail.service;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;

@RunWith(SpringRunner.class)
@SpringBootTest
class MailServiceTest {

    @Resource
    private MailService mailService;

    @Resource
    private TemplateEngine templateEngine;

    @Test
    public void testTemplateMail() throws MessagingException {
        Context context = new Context();
        context.setVariable("id", "001");

        String emailContent = templateEngine.process("emailTemplate", context);
        mailService.sendHtmlMail("YifanLiGeek@gmail.com", "这是一个模板邮件。", emailContent);
    }
}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

你好,这是一封验证邮件,感谢您的注册。请点击以下链接完成注册。感谢您的支持。

<a href="#" th:href="@{http://www.ityouknow.com/register/{id}(id=${id})}">激活账户</a>

</body>
</html>



异常处理。

package com.geek.springbootmail.service;

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.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

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

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {

        logger.info("发送静态邮件开始。{}, {}, {}, {}, {}", to, subject, content, rscPath, rscId);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content, true);

            FileSystemResource fileSystemResource = new FileSystemResource(new File(rscPath));
            mimeMessageHelper.addInline(rscId, fileSystemResource);

            javaMailSender.send(mimeMessage);

            logger.info("发送静态图片邮件成功。");

        } catch (MessagingException e) {

            logger.error("发送静态邮件失败。", e);

            e.printStackTrace();
        }

    }
}



常见错误。

https://help.mail.163.com/faqDetail.do?code=d7a5dc8471cd0c0e8b4b8f4f8e49998b374173cfe9171305fa1ce630d7f67ac28218e37dcd9adbaa

退信代码说明: 
  •554 DT:SPM 发送的邮件内容包含了未被许可的信息,或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件;
如果您是客户端或者程序发送正常邮件,被判定垃圾邮件的大部分原因是因为ip被多个RBL拉黑,您可以在此处查看ip是否被拉黑,如果被拉黑,您可以选择在对应网站申诉,或者联系您的网络运营商,服务器提供商,申请更换发信ip。

  •421 HL:REP 该IP发送行为异常,存在接收者大量不存在情况,被临时禁止连接。请检查是否有用户发送病毒或者垃圾邮件,并核对发送列表有效性;
  •421 HL:ICC 该IP同时并发连接数过大,超过了网易的限制,被临时禁止连接。请检查是否有用户发送病毒或者垃圾邮件,并降低IP并发连接数量;
  •421 HL:IFC 该IP短期内发送了大量信件,超过了网易的限制,被临时禁止连接。请检查是否有用户发送病毒或者垃圾邮件,并降低发送频率;
  •421 HL:MEP 该IP发送行为异常,存在大量伪造发送域域名行为,被临时禁止连接。请检查是否有用户发送病毒或者垃圾邮件,并使用真实有效的域名发送;
  •450 MI:CEL 发送方出现过多的错误指令。请检查发信程序;
  •450 MI:DMC 当前连接发送的邮件数量超出限制。请减少每次连接中投递的邮件数量;
  •450 MI:CCL 发送方发送超出正常的指令数量。请检查发信程序;
  •450 RP:DRC 当前连接发送的收件人数量超出限制。请控制每次连接投递的邮件数量;
  •450 RP:CCL 发送方发送超出正常的指令数量。请检查发信程序;
  •450 DT:RBL 发信IP位于一个或多个RBL里。请参考http://www.rbls.org/关于RBL的相关信息;
  •450 WM:BLI 该IP不在网易允许的发送地址列表里;
  •450 WM:BLU 此用户不在网易允许的发信用户列表里;
  •451 DT:SPM ,please try again 邮件正文带有垃圾邮件特征或发送环境缺乏规范性,被临时拒收。请保持邮件队列,两分钟后重投邮件。需调整邮件内容或优化发送环境;
  •451 Requested mail action not taken: too much fail authentication 登录失败次数过多,被临时禁止登录。请检查密码与帐号验证设置;
  •451 RP:CEL 发送方出现过多的错误指令。请检查发信程序;
  •451 MI:DMC 当前连接发送的邮件数量超出限制。请控制每次连接中投递的邮件数量;
  •451 MI:SFQ 发信人在15分钟内的发信数量超过限制,请控制发信频率;
  •451 RP:QRC 发信方短期内累计的收件人数量超过限制,该发件人被临时禁止发信。请降低该用户发信频率;
  •451 Requested action aborted: local error in processing 系统暂时出现故障,请稍后再次尝试发送;
  •500 Error: bad syntaxU 发送的smtp命令语法有误;
  •550 MI:NHD HELO命令不允许为空;
  •550 MI:IMF 发信人电子邮件地址不合规范。请参考http://www.rfc-editor.org/关于电子邮件规范的定义;
  •550 MI:SPF 发信IP未被发送域的SPF许可。请参考http://www.openspf.org/关于SPF规范的定义;
  •550 MI:DMA 该邮件未被发信域的DMARC许可。请参考http://dmarc.org/关于DMARC规范的定义;
  •550 MI:STC 发件人当天的连接数量超出了限定数量,当天不再接受该发件人的邮件。请控制连接次数;
  •550 RP:FRL 网易邮箱不开放匿名转发(Open relay);
  •550 RP:RCL 群发收件人数量超过了限额,请减少每封邮件的收件人数量;
  •550 RP:TRC 发件人当天内累计的收件人数量超过限制,当天不再接受该发件人的邮件。请降低该用户发信频率;
  •550 DT:SPM 邮件正文带有很多垃圾邮件特征或发送环境缺乏规范性。需调整邮件内容或优化发送环境;
  •550 Invalid User 请求的用户不存在;
  •550 User in blacklist 该用户不被允许给网易用户发信;
  •550 User suspended 请求的用户处于禁用或者冻结状态;
  •550 Requested mail action not taken: too much recipient  群发数量超过了限额;
  •552 Illegal Attachment 不允许发送该类型的附件,包括以.uu .pif .scr .mim .hqx .bhx .cmd .vbs .bat .com .vbe .vb .js .wsh等结尾的附件;
  •552 Requested mail action aborted: exceeded mailsize limit 发送的信件大小超过了网易邮箱允许接收的最大限制;
  •553 Requested action not taken: NULL sender is not allowed 不允许发件人为空,请使用真实发件人发送;
  •553 Requested action not taken: Local user only  SMTP类型的机器只允许发信人是本站用户;
  •553 Requested action not taken: no smtp MX only  MX类型的机器不允许发信人是本站用户;
  •553 authentication is required  SMTP需要身份验证,请检查客户端设置;
  •554 DT:SUM 信封发件人和信头发件人不匹配;
  •554 IP is rejected, smtp auth error limit exceed 该IP验证失败次数过多,被临时禁止连接。请检查验证信息设置;
  •554 HL:IHU 发信IP因发送垃圾邮件或存在异常的连接行为,被暂时挂起。请检测发信IP在历史上的发信情况和发信程序是否存在异常;
  •554 HL:IPB 该IP不在网易允许的发送地址列表里;
  •554 MI:STC 发件人当天内累计邮件数量超过限制,当天不再接受该发件人的投信。请降低发信频率;
  •554 MI:SPB 此用户不在网易允许的发信用户列表里;
  •554 IP in blacklist 该IP不在网易允许的发送地址列表里。


todo。

  • 独立微服务。

  • 异常处理。

  • 定时重试。

  • 异步发送。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用 Spring Boot 的邮件发送功能来发送电子邮件。首先,你需要在项目的依赖中添加 Spring Boot 的邮件依赖。在 `pom.xml` 文件中添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 接下来,你需要在配置文件中配置邮件相关的属性。在 `application.properties`(或 `application.yml`)文件中添加以下属性: ```properties # 邮件服务器主机名 spring.mail.host=your-mail-host # 邮件服务器端口 spring.mail.port=your-mail-port # 邮件发送者用户名 spring.mail.username=your-username # 邮件发送者密码 spring.mail.password=your-password # 邮件发送者地址 spring.mail.from=your-email-address ``` 现在,你可以在你的代码中使用 `JavaMailSender` 接口来发送邮件。你可以注入 `JavaMailSender` 接口的实例,并使用 `send()` 方法发送邮件。以下是一个简单的示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); javaMailSender.send(message); } } ``` 你可以在需要发送邮件的地方调用 `sendEmail()` 方法,并传入收件人地址、邮件主题和邮件内容。 这是使用 Spring Boot 发送邮件的基本步骤。你可以根据自己的需求进行进一步的定制和配置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lyfGeek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值