侧边栏壁纸
博主头像
Epoch

Java开发、Python爬虫、微服务、分布式、前端

  • 累计撰写 92 篇文章
  • 累计创建 109 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Spring Boot集成邮件发送功能

Epoch
2020-05-21 / 0 评论 / 0 点赞 / 242 阅读 / 1,172 字 / 正在检测是否收录...

目标:实现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

m4-png.png

sssss.png


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

下载链接:springboot-email.rar

0

评论区