Spring Boot - 发送电子邮件

环境

操作系统:

Windows 10 x64

集成开发环境:

Spring Tool Suite 4 
Version: 4.14.0.RELEASE
Build Id: 202203131612

发送邮件

邮箱设置

我使用的 163 邮箱提供的服务。首先,登录 163 邮箱,设置如下:

  1. 设置 > POP3/SMTP/IMAP

    在这里插入图片描述

  2. 开启 IMAP/SMTP 服务:

    在这里插入图片描述

  3. 使用你的手机发送短信验证:

    在这里插入图片描述

  4. 验证完成,得到授权密码,记住:

    在这里插入图片描述

  5. 邮箱服务设置完成:

    在这里插入图片描述

项目结构

新建 Spring Starter Project,最终项目结构如下:

在这里插入图片描述

配置

项目创建完成,pom.xml 配置文件:

<?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.6.6</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    
    <groupId>com.mk</groupId>
    <artifactId>Spring-Boot-Send-Email</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-Send-Email</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-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

修改 application.yml 配置文件,邮件服务配置参数:

server:
  port: 8080

spring:
  mail:
    host: smtp.163.com
    username: XXX@163.com
    password: XXX
    default-encoding: UTF-8
    protocol: smtp
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

编码

email.html 模板:

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

<body>
    <p>验证码:<span th:text="${code}">{code}</span></p>
</body>
</html>

提供邮件发送服务的控制器类:

package com.mk.controller;

import java.io.File;

import javax.mail.internet.MimeMessage;

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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/email")
@Slf4j
public class EmailController {
    
    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String addresser; // 发信人
    
    private String addressee = "xxx@qq.com"; // 收信人
    
    @Autowired
    private TemplateEngine templateEngine;
    

    @RequestMapping("send-simple-email")
    public long sendSimpleEmail() {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            
            message.setFrom(addresser);
            message.setTo(addressee);
            message.setSubject("一封简单的邮件");
            message.setText("验证码:1234");
            
            jms.send(message);
        } catch (Exception e) {
            log.error("Exception: ", e);
        }
        
        return System.currentTimeMillis();
    }
    
    @GetMapping("send-html-email")
    public long sendHtmlEmail() {
        try {
            MimeMessage message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(addresser);
            helper.setTo(addressee);
            helper.setSubject("一封 HTML 格式的邮件");

            String content = "<p style='color: #00ff00;'>验证码:1234</p>";
            
            helper.setText(content, true);
            
            jms.send(message);
        } catch (Exception e) {
            log.error("Exception: ", e);
        }
        
        return System.currentTimeMillis();
    }
    
    @GetMapping("send-attachment-email")
    public long sendAttachmentEmail() {
        try {
            MimeMessage message = jms.createMimeMessage();
            
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(addresser); 
            helper.setTo(addressee);
            helper.setSubject("一封带附件的邮件");
            helper.setText("附件:光头强的个人简历");
            
            FileSystemResource file = new FileSystemResource(new File("F:/temp/光头强的个人简历.pdf"));
            
            helper.addAttachment("光头强的个人简历.pdf", file);
            jms.send(message);
        } catch (Exception e) {
            log.error("Exception: ", e);
        }
        
        return System.currentTimeMillis();
    }
    
    @GetMapping("send-inline-email")
    public long sendInlineEmail() {
        try {
            MimeMessage message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            helper.setFrom(addresser); 
            helper.setTo(addressee);
            helper.setSubject("一封带静态资源的邮件");
            helper.setText("<img src='cid:img' style='width: 70px; height: 100px;' />", true);
            helper.addInline("img", new FileSystemResource(new File("F:/temp/光头强.png")));
            
            jms.send(message);
        } catch (Exception e) {
            log.error("Exception: ", e);
        }
        
        return System.currentTimeMillis();
    }
    
    @GetMapping("send-template-email")
    public long sendTemplateEmail() {
        try {
            MimeMessage message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            helper.setFrom(addresser); 
            helper.setTo(addressee);
            helper.setSubject("模板邮件");
            
            Context context = new Context();
            context.setVariable("code", "1234");
            
            String template = templateEngine.process("email", context); // 指向模板 templates/email.html
            
            helper.setText(template, true);
            jms.send(message);
        } catch (Exception e) {
            log.error("Exception: ", e);
        }
        
        return System.currentTimeMillis();
    }
}

测试

依次访问:

  1. http://localhost:8080/email/send-simple-email
  2. http://localhost:8080/email/send-html-email
  3. http://localhost:8080/email/send-attachment-email
  4. http://localhost:8080/email/send-inline-email
  5. http://localhost:8080/email/send-template-email

在目标收信人邮箱中,可以收到:

在这里插入图片描述

参考

SpringBoot 发送电子邮件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值