Springboot发送Email

x33g5p2x  于2021-09-25 转载在 Spring  
字(17.0k)|赞(0)|评价(0)|浏览(372)

准备的东西

https://mail.163.com/ 邮箱

需要开通 POP3/SMTP/IMAP服务

163邮箱开通协议->设置->左侧 POP3/SMTP/IMAP

163第一次激活会有一个SMTP授权密码 记得保存下来 后期授权码不会生成了

qq邮箱开通协议->设置账户(大概中间位置)

qq邮箱的授权码在开启 POP3/SMTP服务的时候会给你一个授权码

但是需要注意的是: 更改QQ密码以及独立密码会触发授权码过期,需要重新获取新的授权码。

(只需要关闭POP3/SMTP服务然后在从新开启就又给你一个授权码)

SMTP 的全称是“Simple Mail Transfer Protocol”,即简单邮件传输协议。它是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMTP 协议属于 TCP/IP 协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP 服务器就是遵循 SMTP 协议的发送邮件服务器。

至于其他的协议我们就不用管了

163的SMTP服务地址 : smtp.163.com

qq的SMTP服务地址: smtp.qq.com

… 网上可以查询到

项目结构

Maven

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--测试的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.1.1.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

application.properties

163邮箱(本项目测试采用)

# 邮箱配置  SMTP服务地址
spring.mail.host=smtp.163.com
# 你的163邮箱  (发邮件的人)
spring.mail.username=huanmin123xx@163.com
# 注意这里不是邮箱密码,而是SMTP授权密码
spring.mail.password=KABLPDGHKCBJLNVK
# 这是smtp端口
spring.mail.port=25
# 这是smtp方式请求
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8

qq邮箱

# 邮箱配置  SMTP服务地址
spring.mail.host=smtp.qq.com
# 你的qq邮箱  (发邮件的人)
spring.mail.username=2811789917@qq.com 
# 注意这里不是邮箱密码,而是SMTP授权密码
spring.mail.password=yjbntymziitkdgdi
# 这是smtp端口
spring.mail.port=25
# 这是smtp方式请求
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8

emailTeplate.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
  <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
  <title>注册-测试邮件模板</title>
</head>
<body>
我是<span th:text="${name}"></span>,感谢你的注册,这是一封验证邮件,感谢您的支持。
<br/>

<div th:if="${idImage1!=null}">
<img th:src="${'cid:'+idImage1}" ></img>
</div>
<div th:if="${idImage2!=null}">
<img th:src="${'cid:'+idImage2}" ></img>
</div>

</body>
</html>

test.doc

内容随意都行 反正就是一个附件而已

timg.jpg

随便图片都行 但是图片不要太大

MailServiceUtils

package com.email.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
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.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Map;

@Service
public class MailServiceUtils {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

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

    @Autowired
    private JavaMailSender mailSender;

    /** * 简单文本邮件 * @param to 接收者邮件 (可以多个 也就是群发) * @param subject 邮件主题名称 * @param contnet 邮件内容 * @param filePaths 邮件附件 (可以发送多个附件) */
    public void sendTextMailText( String subject, String contnet, List<String> filePaths,String... to){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(contnet);
            helper.setFrom(from.trim());
            if (filePaths!=null&&filePaths.size()>0){
                for (String filePath : filePaths) {
                    FileSystemResource file = new FileSystemResource(new File(filePath));
                    String fileName = file.getFilename();
                    helper.addAttachment(fileName, file);
                }
            }

            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        logger.info("发送静态邮件成功!");
    }

    /** * 简单文本邮件 * @param to (可以多个 也就是群发) * @param subject 邮件主题名称 * @param contnet 邮件内容 */
    public void sendTextMailText( String subject, String contnet,String... to){
        this.sendTextMailText( subject,  contnet,null,to);
    }

    /** * HTML 邮件 可以添加附件 和图片 * @param subject 邮件主题名称 * @param contnet 邮件内容 * @param filePaths 邮件附件 (可以发送多个附件) * @param images HTML图片 (可以多个 但是要合HTML内的id一 一对应) * @param to (可以多个 也就是群发) */
    public void sendHtmlMail(String subject, String contnet,List<String> filePaths,Map<String,String> images,String... to) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(contnet, true);
            helper.setFrom(from.trim());

            ///添加图片

            if (images!=null&&images.size()>0) {

                for (Map.Entry<String, String> stringStringEntry : images.entrySet()) {
                    FileSystemResource res = new FileSystemResource(new File(stringStringEntry.getValue())); //value 就是路径
                    helper.addInline(stringStringEntry.getKey(), res);  //key 就是对应 html 图片里设置的占位符的 位置 id
                }

            }

            // 添加附件
            if (filePaths!=null&&filePaths.size()>0){
                for (String filePath : filePaths) {
                    FileSystemResource file = new FileSystemResource(new File(filePath));
                    String fileName = file.getFilename();
                    helper.addAttachment(fileName, file);
                }
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        logger.info("发送静态邮件成功!");
    }

    /** * HTML 邮件 可以添加附件 * @param subject 邮件主题名称 * @param contnet 邮件内容 * @param filePaths 邮件附件 (可以发送多个附件) * @param to (可以多个 也就是群发) */
    public void sendHtmlMail(String subject, String contnet,List<String> filePaths,String... to) {
        this.sendHtmlMail(subject,contnet,filePaths,null,to);

    }

    /** * HTML 邮件 可以添加 图片 * @param subject 邮件主题名称 * @param contnet 邮件内容 * @param images HTML图片 (可以多个 但是要合HTML内的id一 一对应) * @param to (可以多个 也就是群发) */
    public void sendHtmlMail(String subject, String contnet,Map<String,String> images,String... to) {
        this.sendHtmlMail(subject,contnet,null,images,to);

    }


// /**
// * HTML 文本邮件
// * @param to 接收者邮件
// * @param subject 邮件主题
// * @param contnet HTML内容
// * @throws MessagingException
// */
// public void sendHtmlMailTemplate(String to, String subject, String contnet, String rscPath, String rscId) {
// MimeMessage message = mailSender.createMimeMessage();
//
// try {
// MimeMessageHelper helper = new MimeMessageHelper(message, true);
//
// helper.setTo(to);
// helper.setSubject(subject);
// helper.setText(contnet, true);
// helper.setFrom(from);
// FileSystemResource res = new FileSystemResource(new File(rscPath));
// helper.addInline(rscId, res);
// mailSender.send(message);
// } catch (MessagingException e) {
// e.printStackTrace();
// }
// logger.info("发送静态邮件成功!");
// }

    /** * HTML Template 邮件 附件+图片 * @param to 接收者邮件 * @param subject 邮件主题 * @param contnet HTML内容 * @throws MessagingException */
    public void sendHtmlMailTemplate( String subject, String contnet, List<String> filePaths,Map<String,String> images,String... to) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(contnet, true);
            helper.setFrom(from.trim());
            ///添加图片

            if (images!=null&&images.size()>0) {

                for (Map.Entry<String, String> stringStringEntry : images.entrySet()) {
                    FileSystemResource res = new FileSystemResource(new File(stringStringEntry.getValue())); //value 就是路径
                    helper.addInline(stringStringEntry.getKey(), res);  //key 就是对应 html 图片里设置的占位符的 位置 id
                }

            }
            // 添加附件
            if (filePaths!=null&&filePaths.size()>0){
                for (String filePath : filePaths) {
                    FileSystemResource file = new FileSystemResource(new File(filePath));
                    String fileName = file.getFilename();
                    helper.addAttachment(fileName, file);
                }
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        logger.info("发送静态邮件成功!");
    }

    public void sendHtmlMailTemplate( String subject, String contnet,Map<String,String> images,String... to) {
        this.sendHtmlMailTemplate(subject,contnet,null,images,to);
    }

    public void sendHtmlMailTemplate( String subject, String contnet, List<String> filePaths,String... to) {
        this.sendHtmlMailTemplate(subject,contnet,filePaths,null,to);
    }

}

ResourceFileUtil

package com.email.utils;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

/** * @Description: 项目静态资源文件工具类 * 仅可用于包含在web项目中的资源文件路径,资源文件必须放置于 web 模块下 * @Author: junqiang.lu * @Date: 2019/1/4 */
public class ResourceFileUtil {

    /** * 获取资源绝对路径 (就只使用这个 ) * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
    public static String getAbsolutePath(String relativePath) throws FileNotFoundException {
        return getFile(relativePath).getAbsolutePath();
    }

    /** * 获取资源文件 * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
    public static File getFile(String relativePath) throws FileNotFoundException {
        if (relativePath == null || relativePath.length() == 0) {
            return null;
        }
        if (relativePath.startsWith("/")) {
            relativePath = relativePath.substring(1);
        }
        File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX
                + relativePath);

        return file;
    }


    /** * 获取资源父级目录 * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
    public static String getParent(String relativePath) throws FileNotFoundException {
        return getFile(relativePath).getParent();
    }

    /** * 获取资源文件名 * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
    public static String getFileName(String relativePath) throws FileNotFoundException {
        return getFile(relativePath).getName();
    }

}

EmailAppliction

package com.email;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EmailAppliction {
    public static void main(String[] args) {
        SpringApplication.run(EmailAppliction.class,args);
    }
}

MailServiceUtilsTest

下面的邮箱发送 因为是测试所以都是给自己发送的

在 application.properties里写的邮箱是发送的方 而在下面代码中的邮箱是接收方 自行修改

注意: 发送方和接收方邮箱必须是一个类型的 比如: 都是163邮箱 否则邮箱发送虽然不报错,但是邮件实际是发送不到目的地的

本项目测试采用163邮箱

package com.email.Test;

import com.email.service.MailServiceUtils;
import com.email.utils.ResourceFileUtil;
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 org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceUtilsTest {

    @Autowired
    private MailServiceUtils mailService;

    @Resource
    private TemplateEngine templateEngine;

// 纯文本方式
    @Test
    public void sendTextMailText(){
        mailService.sendTextMailText("测试springbootimail-主题","测试spring boot imail - 内容","huanmin123xx@163.com");
    }

    // 文本附件的方式
    @Test
    public void sendTextMailText1() throws FileNotFoundException {
        String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";
        List<String> list= new ArrayList<>();
        list.add(filePath);
        list.add(filePath);
        mailService.sendTextMailText("测试springbootimail-主题","测试spring boot imail - 内容",list,"huanmin123xx@163.com");
    }

    // HTML发送邮件 可以带附件 + 图片

    @Test
    public void sendHtmlMail() throws FileNotFoundException {

        //添加图片
        Map<String,String>  map=new HashMap();
        map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");
        map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");
        //附件方式
        List<String> list= new ArrayList<>();
        String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";
        list.add(filePath);
        list.add(filePath);

        String content = "<html>" +
                "<body>" +
                "<h3>hello world</h3>" +
                "<h1>html</h1>" +
                "<h1>图片-附件-邮件</h1>" +
                "<img src='cid:img1'></img>" +    //此img1 对应上面 map的img1 否则图片找不到
                "<img src='cid:img2'></img>" +
                "<body>" +
                "</html>";

        mailService.sendHtmlMail("这是一封图片邮件",content,list, map,"huanmin123xx@163.com");
    }

    // HTML发送邮件 只带附件

    @Test
    public void sendHtmlMail1() throws FileNotFoundException {

        //附件方式
        List<String> list= new ArrayList<>();
        String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";
        list.add(filePath);
        list.add(filePath);
        String content = "<html>" +
                "<body>" +
                "<h3>hello world</h3>" +
                "<h1>html</h1>" +
                "<h1>附件邮件</h1>" +
                "<body>" +
                "</html>";
        mailService.sendHtmlMail("这是一封图片邮件",content,list,"huanmin123xx@163.com");
    }
    // HTML发送邮件 只带图片
    @Test
    public void sendHtmlMail2() throws FileNotFoundException {
        //添加图片
        Map<String,String>  map=new HashMap();
        map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");
        map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");
        String content = "<html>" +
                "<body>" +
                "<h3>hello world</h3>" +
                "<h1>html</h1>" +
                "<h1>图片邮件</h1>" +
                "<img src='cid:img1'></img>" +    //此img1 对应上面 map的img1 否则图片找不到
                "<img src='cid:img2'></img>" +
                "<body>" +
                "</html>";
        mailService.sendHtmlMail("这是一封图片邮件",content,map,"huanmin123xx@163.com");
    }


    // 使用Template模板方式 带附件 带图片
    @Test
    public void testTemplateMailTest1() throws FileNotFoundException {
        //添加图片
        Map<String,String>  map=new HashMap();
        map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");
        map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");
        //附件方式
        List<String> list= new ArrayList<>();
        String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";
        list.add(filePath);
        list.add(filePath);

        Context context = new Context();
        // 模本内容填充
        context.setVariable("name","huanmin123xx");
            // 模板名称
        String emailContent = templateEngine.process("emailTeplate", context);
        mailService. sendHtmlMailTemplate("这是一封HTML模板邮件",emailContent,list,map,"huanmin123xx@163.com");

    }

    // 使用Template模板方式 带图片
    @Test
    public void testTemplateMailTest2() throws FileNotFoundException {
        //添加图片
        Map<String,String>  map=new HashMap();
        map.put("img1",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");
        map.put("img2",ResourceFileUtil.getAbsolutePath("templates") + File.separator + "timg.jpg");

        Context context = new Context();
        // 模本内容填充
        context.setVariable("name","huanmin123xx");
        context.setVariable("idImage1","img1"); //此img1 对应上面 map的img1 否则图片找不到
        context.setVariable("idImage2","img2");
        // 模板名称
        String emailContent = templateEngine.process("emailTeplate", context);
        mailService. sendHtmlMailTemplate("这是一封HTML模板邮件",emailContent,map,"huanmin123xx@163.com");

    }

    // 使用Template模板方式 带附件
    @Test
    public void testTemplateMailTest3() throws FileNotFoundException {

        //附件方式
        List<String> list= new ArrayList<>();
        String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";
        list.add(filePath);
        list.add(filePath);

        Context context = new Context();
        // 模本内容填充
        context.setVariable("name","huanmin123xx");
        // 模板名称
        String emailContent = templateEngine.process("emailTeplate", context);
        mailService. sendHtmlMailTemplate("这是一封HTML模板邮件",emailContent,list,"huanmin123xx@163.com");

    }

}

uanmin123xx@163.com");

    }

    // 使用Template模板方式 带附件
    @Test
    public void testTemplateMailTest3() throws FileNotFoundException {

        //附件方式
        List<String> list= new ArrayList<>();
        String filePath = ResourceFileUtil.getAbsolutePath("templates") + File.separator + "test.doc";
        list.add(filePath);
        list.add(filePath);

        Context context = new Context();
        // 模本内容填充
        context.setVariable("name","huanmin123xx");
        // 模板名称
        String emailContent = templateEngine.process("emailTeplate", context);
        mailService. sendHtmlMailTemplate("这是一封HTML模板邮件",emailContent,list,"huanmin123xx@163.com");

    }

}

点赞 -收藏-关注-便于以后复习和收到最新内容有其他问题在评论区讨论-或者私信我-收到会在第一时间回复如有侵权,请私信联系我感谢,配合,希望我的努力对你有帮助^_^

相关文章