springboot整合mail邮件

在项目的维护过程中,通常会加入邮箱的报警功能,当系统出现异常、宕机等问题时,及时能将问题以邮箱的形式发送给运维或

者开发人员,从而快速解决系统问题,保证系统的正常运行。

本文中将mail整合到springboot中,实现邮件的发送。在springboot中发送邮件中,使用的是spring所提供的包

org.springframework.mail.javamail.JavaMailSender,该包中提供了许多简单易容的方法,发送邮件的方式有多种,如:简单的

邮件、HTML格式的邮件、带附件的邮件。

springboot整合邮件的步骤如下:

1、引入依赖

本版号:

springContext.version:5.1.3.RELEASE

mail.version:1.4.7

beetl.version:2.9.7

<!--邮件发送依赖包-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${springContext.version}</version>
</dependency>
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>${mail.version}</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
     <groupId>com.ibeetl</groupId>
     <artifactId>beetl</artifactId>
     <version>${beetl.version}</version>
</dependency>

2、添加配置文件(yml文件配置方式)

username为邮箱地址,password为邮箱授权码(邮箱授权码获取方式如下图所示)。

spring:
  # spring整合email配置
  mail:
    host: smtp.qq.com
    username: XXXXXX@qq.com
    password: XXXXXX

邮箱授权码获取方式(以QQ邮箱为例):

3、添加配置类,实现邮箱的发送

配置类:

package com.aaron.config.email;

import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.io.IOException;

/**
 * @author: Aaron
 * @description: 邮件配置
 * @date: Create in 2019/5/23 下午 04:43
 */
@Configuration
@ComponentScan(value = "com.aaron.utils")
public class EmailConfig {

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

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

    @Value("${spring.mail.password}")
    private String authWord;

    /**
     * 在这里可以声明不同的邮件服务器主机,
     * 通常是SMTP主机,而具体的用户名和时授权码则建议在业务中从数据库查询
     *
     * @return
     */
    @Bean(name = "mainSender")
    JavaMailSenderImpl javaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(host);
        // 设置发送人邮箱和授权码
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(authWord);
        return javaMailSender;
    }

    /**
     * 配置模板引擎
     *
     * @return
     * @throws IOException
     */
    @Bean
    GroupTemplate groupTemplate() throws IOException {
        // 指定加载模板资源的位置 指定在classpath:beetl下
        ClasspathResourceLoader loader = new ClasspathResourceLoader("beetl");
        // beetl配置 这里采用默认的配置
        org.beetl.core.Configuration configuration = org.beetl.core.Configuration.defaultConfiguration();
        return new GroupTemplate(loader, configuration);
    }
}

工具类:

package com.aaron.utils;

import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

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

/**
 * @author: Aaron
 * @description:
 * @date: Create in 2019/5/23 下午 04:44
 */
@Component
public class EmailUtil {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private GroupTemplate groupTemplate;

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

    /**
     * @param to
     * @param subject
     * @param content
     * @description: 发送简单邮件
     */
    public void sendTextMessage(String to, String subject, String content) {

        // 实例化消息对象
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(username);
        msg.setTo(to);
        msg.setSubject(subject);
        msg.setText(content);
        try {
            // 发送消息
            this.mailSender.send(msg);
            System.out.println("邮件发送成功");
        } catch (MailException e) {
            System.out.println("邮件发送失败:" + e.getMessage());
        }
    }

    /**
     * @param to
     * @param subject
     * @param content
     * @param files
     * @description: 发送带附件的邮件
     */
    public void sendEmailWithAttachments(String to, String subject,
                                         String content, Map<String, File> files) {
        try {
            // 实例化消息对象
            MimeMessage message = mailSender.createMimeMessage();
            // 需要指定第二个参数为true 代表创建支持可选文本,内联元素和附件的多部分消息
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
            helper.setFrom(username);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
            // 传入附件
            for (Map.Entry<String, File> entry : files.entrySet()) {
                helper.addAttachment(entry.getKey(), entry.getValue());
            }
            // 发送消息
            this.mailSender.send(message);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("邮件发送失败:" + e.getMessage());
        }
    }

    /**
     * @param to
     * @param subject
     * @param content
     * @param file
     * @description: 发送带内嵌资源的邮件
     */
    public void sendEmailWithInline(String to, String subject, String content, File file) {
        try {
            // 实例化消息对象
            MimeMessage message = mailSender.createMimeMessage();
            // 需要指定第二个参数为true 代表创建支持可选文本,内联元素和附件的多部分消息
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
            helper.setFrom(username);
            helper.setTo(to);
            helper.setSubject(subject);
            // 使用true标志来指示包含的文本是HTML 固定格式资源前缀 cid:
            helper.setText("<html><body><img src='cid:image'></body></html>", true);
            // 需要先指定文本 再指定资源文件
            FileSystemResource res = new FileSystemResource(file);
            helper.addInline("image", res);
            // 发送消息
            this.mailSender.send(message);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("邮件发送失败:" + e.getMessage());
        }
    }

    /**
     * @param to
     * @param subject
     * @param content
     * @description: 使用模板邮件
     */
    public void sendEmailByTemplate(String to, String subject, String content) {
        try {
            Template t = groupTemplate.getTemplate("template.html");
            t.binding("subject", subject);
            t.binding("content", content);
            String text = t.render();
            // 实例化消息对象
            MimeMessage message = mailSender.createMimeMessage();
            // 指定 utf-8 防止乱码
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
            helper.setFrom(username);
            helper.setTo(to);
            helper.setSubject(subject);
            // 为true 时候 表示文本内容以 html 渲染
            helper.setText(text, true);
            this.mailSender.send(message);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            // 消息发送失败可以做对应的处理
            System.out.println("邮件发送失败:" + e.getMessage());
        }
    }
}

html模板(本文中使用beetl模板),放在resources目录下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
<h1>邮件主题:<span style="color: chartreuse"> ${subject}</span></h1>
<h4 style="color: blueviolet">${content}</h4>
</body>
</html>

4、通过测试,验证邮件是否发送成功。

单元测试类:

package com.aaron.emailtest;

import com.aaron.utils.EmailUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Aaron
 * @description:
 * @date: Create in 2019/5/23 下午 05:32
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {

    @Autowired
    private EmailUtil emailUtil;

    // 接收方邮箱地址
    private static final String to = "XXXXXX@qq.com";

    /**
     * 发送简单邮件
     */
    @Test
    public void sendMessage() {
        emailUtil.sendTextMessage(to, "发送简单邮件", "Hello Spring Email");
    }

    /**
     * 发送带附件的邮件
     */
    @Test
    public void sendEmailWithAttachments() {
        Map<String, File> fileMap = new HashMap<>();
        fileMap.put("image1.jpg", new File("E:\\Aaron\\picture\\附件1.png"));
        fileMap.put("image2.jpg", new File("E:\\Aaron\\picture\\附件2.png"));
        emailUtil.sendEmailWithAttachments(to, "发送带附件的邮件"
                , "Hello Spring Email", fileMap);
    }

    /**
     * 发送带内嵌资源的邮件
     */
    @Test
    public void sendEmailWithInline() {
        emailUtil.sendEmailWithInline(to, "发送带内嵌资源的邮件"
                , "Hello Spring Email", new File("E:\\Aaron\\picture\\附件3.png"));
    }

    /**
     * 使用模板邮件
     */
    @Test
    public void sendEmailByTemplate() {
        emailUtil.sendEmailByTemplate(to, "使用模板邮件", "Hello Spring Email");
    }
}

测试结果:

 

 

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring Boot可以很方便地实现邮件发送功能,下面是整合Spring Boot和Java Mail的步骤: 1. 添加依赖:在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 配置邮件发送信息:在`application.properties`文件中配置邮件发送的相关信息,例如: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=your-email@example.com spring.mail.password=your-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 创建邮件发送服务:创建一个邮件发送服务类,例如`MailService`,并注入`JavaMailSender`: ```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 MailService { @Autowired private JavaMailSender javaMailSender; public void sendEmail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(content); javaMailSender.send(message); } } ``` 4. 使用邮件发送服务:在需要发送邮件的地方,注入`MailService`并调用`sendEmail`方法来发送邮件: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class EmailController { @Autowired private MailService mailService; @RequestMapping("/sendEmail") public String sendEmail() { String to = "recipient@example.com"; String subject = "Test Email"; String content = "This is a test email."; mailService.sendEmail(to, subject, content); return "Email sent successfully"; } } ``` 这样,当访问`/sendEmail`接口时,就会发送一封测试邮件到指定的收件人邮箱。 以上就是Spring Boot整合Java Mail实现邮件发送的基本步骤。你可以根据自己的需求进一步定制邮件内容、添加附件等功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值