springboot实现邮件发送

首先新建一个maven项目

1.在pom.xml中一如jar包

<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>

application.yml文件配置如下

spring:
  mail:
    host: smtp.qq.com
    username: 1490512621@qq.com   #发送邮件的用户名
#   password指的是邮箱授权码,可以在各大邮箱的个人中心找到
    password: wmowpegktopagdca
    default-encoding: utf-8

2.邮件发送方法,包含发送简单的文本文件,发送一个HTML邮件,发送一个带附件的邮件,发送图片的邮件和模板邮件的测试用例

package com.example.mail;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

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.Service;

@Service
public class MailService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	//这个是发送人的用户名,如1490512620@qq.com
    @Value("${spring.mail.username}")
    private String from;
    
    //用来发送邮件
    @Autowired
    private JavaMailSender mailSender;
    
	 /**
     * @return void
     * @Description //TODO 发送简单的文本文件,to:收件人 subject:主题 content:内容
     * @Date 11:00 2018/10/30
     * @Param [to, subject, content]
     **/
    public void sendSimpleMail (String to, String subject, String content){
        //创建一个简单的文本文件实例
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        mailSender.send(mailMessage);
    }
    
    /**
     * @return void
     * @Description //TODO 发送一个HTML邮件,to:收件人 subject:主题 content:内容
     * @Date 15:01 2018/10/30
     * @Param [to, subject, content]
     **/
    public void sentHtmlMail (String to, String subject, String content ) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);

        //设置成true,会将这封邮件里边的html标签正常处理,否则会被当成文本处理
        helper.setText(content, true);

        mailSender.send(message);
    }
    
    /**
     * @return void
     * @Description //TODO 发送一个带附件的邮件,to:收件人,subject:主题,content:主题,filePath:附件的路径(测试可以发送文件和图片,其中图片需要点击预览查看)
     * 收件人:helper.setTo(to);抄送:helper.setCc(cc);密送:helper.setBcc(bcc);
     * @Date 15:26 2018/10/30
     * @Param [to, subject, content, filePath]
     **/
    public void sendAttachmentMail(String to, String subject, String content, String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        //设置邮件的一些基本信息
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content);

        //设置附件
        FileSystemResource file = new FileSystemResource(new File(filePath));
        String filename = file.getFilename();
        helper.addAttachment(filename, file);

        //发送邮件
        mailSender.send(message);
    }
    
    /**
     * 发送图片的邮件,该方法发送的图片直接展示出来 不用预览
     * @param to
     * @param subject
     * @param content
     * @param rscId
     * @param rscPath
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscId, String rscPath) {
        MimeMessage message = mailSender.createMimeMessage();

        logger.info("静态邮件发送开始:{}, {}, {}, {}, {}", to, subject, content, rscId, rscPath);
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            //构造邮件内部的图片资源
            FileSystemResource file = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, file);

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

}

3.测试方法

package com.example.demo;

import javax.mail.MessagingException;

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 com.example.mail.MailService;

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

	@Autowired
    private MailService mailService;
	
	@Autowired
    private TemplateEngine engine;
	
	@Test
	public void contextLoads() {
	}

	@Test
    public void sendSimpleMailTest(){
        mailService.sendSimpleMail("1490512621@qq.com", "Dear", "I love you!");
    }
	
	@Test
    public void sendHtmlMailTest() throws MessagingException {
        String content = "<html>\n" +
                "<body>\n" + "<h3>这是一封HTML邮件</h3>"
                + "</body>\n" + "</html>";
        mailService.sentHtmlMail("1490512621@qq.com", "HTML邮件", content);
    }
	
	@Test
    public void sendAttachmentMail() throws MessagingException {
        String filePath = "E:\\1.png";
        String c = "ZZ!";
        mailService.sendAttachmentMail("1490512621@qq.com", "Test", c, filePath);
    }
	
	@Test
    public void sendInlineResourceMainTest() {
        String filePath = "E:\\\\1.png";
        String rscId = "chen";

        //img解析出来的写法就是 <img src = 'cid:chen'></img>
        String content = "<html><body>带图片的邮件:<img src=\'cid:" +
                rscId + "\'></img></body></html>";

        mailService.sendInlineResourceMail("1490512621@qq.com", "a", content, rscId, filePath);
    }
	
	/**
	 * 类似于注册 发送模板邮件激活
	 * @throws MessagingException
	 */
	@Test
    public void sendTempleteMail () throws MessagingException {
        Context context = new Context();
        context.setVariable("id", 001);

        String emailContent = engine.process("mailTemplete", context);
        mailService.sentHtmlMail("1490512621@qq.com", "模板", emailContent);
    }
	
}

4.模板邮件激活使用的html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>邮件模板</title>
</head>
<body>
    <p>您好,感谢您的注册,这是一份验证邮件,请点击下面的连接完成注册,感谢您的配合!</p>
    <a href="#" th:href="@{https://blog.csdn.net/QCIWYY/{id}(id=${id})}">激活账号</a>
</body>
</html>

源码地址参考:https://download.csdn.net/download/qciwyy/10753385

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值