码上焚香

Yahocen

SpringBoot 发送邮件

40
2024-05-10

开发环境:Maven + IDE + SpringBoot + 微软邮箱

引入SpringBoot的邮件依赖

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

在 application.properties 配置文件中添加邮件的相关配置

#SMTP 服务器地址 如何是其他邮箱 请自行搜索
spring.mail.host=smtp.live.com
#邮箱地址
spring.mail.username=yahocen@hotmail.com
#邮箱密码 如何开启了授权码 就填写授权码
spring.mail.password=xxxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

编写发送邮件类 SendMail.java

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

import javax.mail.MessagingException;
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.stereotype.Service;

/**
 * @ClassName:   SendMail   
 * @Description: 发送邮件
 * @author:      Yahocen
 * @date:        2018年9月29日 下午6:49:22
 */
@Service
public class SendMail {

    @Autowired
    private JavaMailSender mailSender;

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

    /**
     * 发送文本邮件
     * @param from 发送者地址
     * @param to 接受者体质
     * @param title
     * @param content
     */
    public void sendSimpleMail(String to, String title, String content) {
        SimpleMailMessage message = new SimpleMailMessage(); 
        message.setFrom(this.from); 
        message.setTo(to);
        message.setSubject(title);
        message.setText(content); 
        mailSender.send(message);
    }

    /**
     * 发送html格式邮件
     * @param from
     * @param to
     * @param title
     * @param content
     * @return
     */
    public boolean sendHtmlMail(String to, String title, String content) {
        MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
        helper.setFrom(this.from);
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(content, true);
        } catch (MessagingException e) {
        e.printStackTrace();
        return false;
        }
            mailSender.send(message);
            return true;
    }

    /**
     * 发送存在附件的邮件
     * @param from
     * @param to
     * @param title
     * @param content
     * @param html
     * @param filetitle
     * @param file
     * @return
     */
    public boolean sendAttachmentsMail(String to, String title, String content, boolean html, String filetitle, File file) {
        MimeMessage message = null;
            try {
                message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(this.from);
                helper.setTo(to);
                helper.setSubject(title);
                helper.setText(content, html);
                helper.addAttachment(filetitle + file.getName().substring(file.getName().lastIndexOf('.')), file);
            } catch (Exception e){
                e.printStackTrace();
                return false;
            }
            mailSender.send(message);
            return true;
    }

    /**
     * 发送Html格式带有内敛资源的邮件
     * @param from
     * @param to
     * @param title
     * @param content <html><body>带静态资源的邮件内容 图片:<img src='cid:picture(inlineFile.key)' /></body></html>
     * 第二个参数指定发送的是HTML格式,同时cid:是固定的写法
     * @param inlineFile
     * @return
     */
        public boolean sendInlineMail(String to, String title, String content, Map<String, File> inlineFile) {
        MimeMessage message = null;
            try {
                message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(this.from);
                helper.setTo(to);
                helper.setSubject(title);
                helper.setText(content, true);

                inlineFile.forEach((contentId, file) -> {
                    try {
                helper.addInline(contentId,file);
                } catch (MessagingException e) {
                    e.printStackTrace();
            }
                });
            } catch (Exception e){
                e.printStackTrace();
                return false;
            }
            mailSender.send(message);
            return true;
        }

}

测试类 SendMailTest.java

import java.io.File;

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;

/**
 * @ClassName:   BlogApplicationTests   
 * @Description: 测试发送邮件
 * @author:      Yahocen
 * @date:        2018年9月29日 下午6:41:58
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SendMailTest {

    @Autowired
    private SendMail sendMail;

    @Test
    public void sendSimpleMail() {
        sendMail.sendSimpleMail("543754816@qq.com", "这是纯文本邮件标题", "纯文字内容");
    }

    @Test
    public void sendHtmlMail() {
        String html = "<a href='http://yahocen.xyz'>这是一个连接</a>";
        sendMail.sendHtmlMail("543754816@qq.com", "这是html邮件标题", html);
    }

    @Test
    public void sendAttachmentsMail() {
        String html = "<a href='http://yahocen.xyz'>这是一个连接</a>";
        sendMail.sendAttachmentsMail("543754816@qq.com", "这是html邮件标题", html, true, "附件名称", new File("C:\\Users\\yahoc\\Desktop\\照片.jpg"));
    }

}

在SendMail.java中为什么还需要引入from属性,难道配置文件中已经包含了吗?我测试过,如果去掉setFrom会导致错误。我猜想可以在配置文件中配置多个邮箱参数,然后指定from属性进行发送。大家可以自行测试,以上提到的单邮箱已经满足了大多数功能需求。