前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot集成邮件发送功能

Spring Boot集成邮件发送功能

作者头像
背雷管的小青年
发布2020-06-09 15:27:10
7010
发布2020-06-09 15:27:10
举报

目标:实现Spring Boot集成邮件发送功能 工具:IDEA--2020.1 学习目标:实现Spring Boot集成邮件发送功能 本次学习的工程下载链接放到文本最后面

新建一个springboot项目,添加如下相关依赖

   <!--springboot集成邮件功能-->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-mail</artifactId>
   </dependency>
  • 编写邮件服务发送的接口:

package com.xmaven.service;

/**
 * @author Sanji
 */
public interface  MailService {
    /**
     * 发送纯文本邮件
     * @param toAddr 发送给谁
     * @param title 标题
     * @param content 内容
     */
    public void sendTextMail(String toAddr, String title, String content);

    /**
     * 发送 html 邮件
     * @param toAddr
     * @param title
     * @param content 内容(HTML)
     */
    public void sendHtmlMail(String toAddr, String title, String content);

    /**
     *  发送待附件的邮件
     * @param toAddr
     * @param title
     * @param content
     * @param filePath 附件地址
     */
    public void sendAttachmentsMail(String toAddr, String title, String content, String filePath);

    /**
     *  发送文本中有静态资源(图片)的邮件
     * @param toAddr
     * @param title
     * @param content
     * @param rscPath 资源路径
     * @param rscId 资源id (可能有多个图片)
     */
    public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId);

}
  • 编写邮件服务发送的实现类:

package com.xmaven.service.impl;

import com.xmaven.service.MailService;
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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
 * @author Sanji
 */
@Component
public class MailServiceImpl implements MailService {

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

    @Autowired
    private JavaMailSender mailSender;

    // 注入常量
    @Value("${mail.fromMail.addr}")
    private String from;

    @Override
    public void sendTextMail(String toAddr, String title, String content) {
        //纯文本发送
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(toAddr);
        message.setSubject(title);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("Text邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送Text邮件时发生异常!", e);
        }
    }

    @Override
    public void sendHtmlMail(String toAddr, String title, String content) {
        // html 邮件对象
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddr);
            helper.setSubject(title);
            helper.setText(content, true);

            mailSender.send(message);
            logger.info("html邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常!", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String toAddr, String title, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddr);
            helper.setSubject(title);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常!", e);
        }
    }

    @Override
    public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddr);
            helper.setSubject(title);
            //记得设置为true,没有的话图片时显示不了的
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            System.out.println(res.getPath());
            helper.addInline(rscId, res);

            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }

}
  • 修改application.yml(原来的是application.properties,更改一下后缀)

spring:
  mail:
    host: smtp.qq.com
    username: 1595021694@qq.com
    password: xxxxxxxxx   #填写自己的获取的授权码
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

#定义的邮件发送方和接收方
mail:
  fromMail:
    addr: 1595021694@qq.com
  receptionMail:
    addr: 178037785@qq.com
  • 在测试类里面进行测试:

package com.xmaven;

import com.xmaven.service.MailService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author Sanji
 */
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootEmailApplicationTests {

    @Value("${mail.receptionMail.addr}")
    private String receptionMailAddr;

    @Autowired
    private MailService mailService;



    /**
     * 测试 文本邮件
     * @throws Exception
     */
    @Test
    public void testSimpleMail() throws Exception {
        mailService.sendTextMail(receptionMailAddr,"测试文本邮箱发送","你好你好!");
    }

    /**
     * 测试 html 邮箱
     * @throws Exception
     */
    @Test
    public void testHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail(receptionMailAddr,"test simple mail",content);
    }

    @Test
    public void sendAttachmentsMail() {
        String filePath="C:\\jetbrains-agent.jar";
        mailService.sendAttachmentsMail(receptionMailAddr, "主题:带附件的邮件", "有附件,请查收!", filePath);
    }

/*这个有些问题图片在邮件中显示不出来,可能是qq邮箱的问题*/
/*
    @Test
    public void sendInlineResourceMail() {
        String rscId = "good";
        String content="<html><body>这是有图片的邮件:<img style='width: 200px;height: 200px;' src=\'cid:" + rscId + "\'></body></html>";
        String imgPath = "C:\\Users\\Sanji\\Pictures\\1.jpg";

        mailService.sendInlineResourceMail(receptionMailAddr, "主题:这是有图片的邮件", content, imgPath, rscId);
    }
*/



}
  • 测试效果如下:
GPT8`}VT30SBQH(2}GC7O26.png
GPT8`}VT30SBQH(2}GC7O26.png
m4-png.png
m4-png.png
_)N`GK8Q2N_YMJ_SGO[EJT6.png
_)N`GK8Q2N_YMJ_SGO[EJT6.png

本文具体参考: https://juejin.im/post/5cb2bb45e51d456e3428c0d7

下载链接:springboot-email.rar

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档