栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用Spring Boot向邮箱发送邮件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Spring Boot向邮箱发送邮件

使用Spring Boot发送邮件
  • 1.引入依赖
    • 2.邮箱配置信息
    • 3.编写测试类实现发送简单的邮件
    • 4.编写测试类实现发送HTML格式的邮件
    • 5.编写测试类实现发送带附件格式的邮件
    • 6.编写测试类实现发送带静态资源的邮件
    • 7.编写测试类实现使用模板发送邮件

1.引入依赖

在pom文件中引入以下jar包依赖。


    org.springframework.boot
    spring-boot-starter-mail

2.邮箱配置信息

在Spring Boot配置文件application.yml中配置邮箱信息;当然邮箱发送人不确定的话,可以通过数据库中创建邮箱配置表来进行存储,这里就不多做介绍了。

server:
  port: 8080
spring:
  mail:
  	# 邮件服务地址,可以配置其他邮箱服务地址,例如:smtp.qq.com
    host: smtp.163.com
    username: 你的邮箱账号
    password: 你的邮箱密码
    properties:
      mail:
        smtp:
          auth: true
          #如果是用 SSL 方式,需要配置如下属性
          starttls:
            enable: true
            required: true
3.编写测试类实现发送简单的邮件

编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人,这里不是在yml配置的邮箱发送人信息的话,可以在业务层逻辑中通过数据库查询。

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailTestController {

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @RequestMapping("sendSimpleTestEmail")
    public String sendSimpleTestEmail() {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo("123456789@qq.com"); // 接收地址
            message.setSubject("一封简单的测试邮件"); // 标题
            message.setText("使用Spring Boot发送测试邮件。"); // 内容
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
4.编写测试类实现发送HTML格式的邮件

编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人。

import javax.mail.internet.MimeMessage;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailTestController{

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @RequestMapping("sendHtmlTestEmail")
    public String sendHtmlTestEmail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("123456789@qq.com"); // 接收地址
            helper.setSubject("一封HTML格式的邮件"); // 标题
            // 带HTML格式的内容
            StringBuffer sb = new StringBuffer("

使用Spring Boot发送HTML格式邮件。

"); helper.setText(sb.toString(), true);//true表示发送HTML格式邮件 jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } }
5.编写测试类实现发送带附件格式的邮件

编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人。发送带附件的邮件和普通邮件相比,其实就只是多了个传入附件的过程。

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailTestController{

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
	
    @RequestMapping("sendAttachmentsTestMail")
    public String sendAttachmentsTestMail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("123456789@qq.com"); // 接收地址
            helper.setSubject("一封带附件的邮件"); // 标题
            helper.setText("详情参见附件内容!"); // 内容
            // 传入附件
            FileSystemResource file = new FileSystemResource(new File("file/项目文档.docx"));//附件相对路径
            helper.addAttachment("项目文档.docx", file);//添加附件到对象中
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
6.编写测试类实现发送带静态资源的邮件

编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人。发送带静态资源的邮件其实就是在发送HTML邮件的基础上嵌入静态资源(比如图片),嵌入静态资源的过程和传入附件类似,唯一的区别在于需要标识资源的cid:

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailTestController{

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
	
    @RequestMapping("sendInlineTestMail")
    public String sendInlineTestMail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("123456789@qq.com"); // 接收地址
            helper.setSubject("一封带静态资源的邮件"); // 标题
            helper.setText("图片:", true); // 内容
            // 传入附件
            FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png"));
            helper.addInline("img", file); //img和图片标签里cid后的名称相对应
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
7.编写测试类实现使用模板发送邮件

编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人在发送验证码等情况下可以创建一个邮件的模板,唯一的变量为验证码。这个例子中使用的模板解析引擎为Thymeleaf,所以首先引入Thymeleaf依赖:


    org.springframework.boot
    >spring-boot-starter-thymeleaf

在template目录下创建一个emailTemplate.html模板:




    
    模板



    您的验证码为{code},该验证码有效期为60秒。


发送模板邮件,本质上还是发送HTML邮件,只不过多了绑定变量的过程。

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

@RestController
@RequestMapping("/email")
public class EmailTestController{

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @Autowired
    private TemplateEngine templateEngine;
	
    @RequestMapping("sendTemplateTestEmail")
    public String sendTemplateTestEmail(String code) {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("123456789@qq.com"); // 接收地址
            helper.setSubject("邮件摸板测试"); // 标题
            // 处理邮件模板
            Context context = new Context();
            context.setVariable("code", code);
            String template = templateEngine.process("emailTemplate", context);
            helper.setText(template, true);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1024175.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号