SpringBoot简单快速实现发送邮件方法和示例(纯文本和富文本html邮件)

2022-11-06 472点热度 0人点赞 0条评论

SpringBoot比较方便能支持JavaMail发送邮件,只需要简单在SpringBoot starter中配置下就可以了,在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。

具体只需要如下3步:

  1. pom添加Starter模块依赖
  2. application.yml/propertiews添加发送的邮箱帐号
  3. 调用JavaMailSender接口发送邮件

添加maven依赖

在 pom.xml 配置文件中加入 spring-boot-starter-mail 依赖:

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

添加邮箱配置参数

spring:
  mail:
    host: smtp.qiye.aliyun.com
    port: 25
    username: [email protected]
    password: yourpassword
    default-encoding: UTF-8
    from: [email protected]
    fromName: 发送人某某名称

调用JavaMailSender接口发送邮件

我把发送邮件整理成了工具类 MailUtils.java,如下:

package com.terrytest.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;

@Service
public class MailUtils {
    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.from}")
    private String mailFrom;
    @Value("${spring.mail.fromName}")
    private String mailFromName;

    /**
     * 发送简单邮件
     *
     * @param toAddress 邮件接受者邮件地址
     * @param title     邮件主题
     * @param text      邮件文本内容
     */
    public void sendSimpleMail(String toAddress, String title, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom(mailFrom);
        message.setFrom(mailFromName + " <" + mailFrom + ">");
        message.setTo(toAddress);
        message.setSubject(title);
        message.setText(text);
        javaMailSender.send(message);
    }

    /**
     * html邮件
     *
     * @param toAddress 邮件接受者邮件地址
     * @param title     邮件主题
     * @param html      邮件Html内容
     * @param inlines   附在邮件正文中的inline图片(不是附件)
     */
    public void sendHtmlMail(String toAddress, String toName, String title, String html, HashMap<String, byte[]> inlines) throws Exception {
        MimeMessage message = null;
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(mailFrom, mailFromName);
        if (toName != null && toName.trim().length() > 0) {
            helper.setTo(new InternetAddress(toAddress, toName));
        } else {
            helper.setTo(toAddress);
        }
        helper.setSubject(title);
        helper.setText(html, true);

        if (inlines != null && inlines.size() > 0) {
            inlines.forEach((s, bytes) -> {
                try {
                    helper.addInline(s, new ByteArrayResource(bytes), "image/jpeg");
                } catch (MessagingException ignored) {
                }
            });
        }

        javaMailSender.send(message);
    }
}

如何使用:

@Autowired
MailUtils mailUtils;

mailUtils.sendSimpleMail("[email protected]", "这是一个title", "这是一个内容");

以上是发送纯文本的邮件,如果要发送Html富文本邮件,使用sendHtmlMail,实际应该会比较复杂(比如使用thymeleaf等渲染出html等),这里只是简单介绍下使用方法,具体根据实际需求自己再丰富下。

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论