spring boot 实现邮件发送

1.在pom文件中添加依赖:如下:

        <!--邮件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!--模板thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2 某个邮箱开启POP3/SMTP服务

以qq邮箱为列:

   . 点击“”设置“”按钮,点击“”账户“面板,选择开启POP3/SMTP服务,如图:

 

开启服务时,会生成一个授权码。记住这个授权码。

yml配置中添加如下配置:注意此处password  不是你邮箱的密码,而是刚刚记下的客户端授权码。

    spring:

          mail:
              host: smtp.qq.com
             username: ************@qq.com
             password: ufvbwptjicaobfab
             default-encoding: UTF-8
             port: 25
             protocol: smtp

   #发件人地址
   mail:
       fromMail:
           addr: *************@qq.com

3.在service层新加MailService类

    代码如下:

  

package com.bh.service;
 
import java.io.File;
 
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.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 org.springframework.stereotype.Service;
 
 
/**
 * @Description:邮件发送类
 * @author hxc
 *
 */
@Service
@Component
public class MailService{
 
    @Autowired
    private JavaMailSender mailSender;
 
    @Value("${mail.fromMail.addr}")
    private String from;
    
    /**
     * @Description:发送简单邮件(收件人,主题,内容都暂时写死)
     * @return
     * @author:hxc
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            System.out.println("简单邮件发送成功!");
        } catch (Exception e) {
            System.out.println("发送简单邮件时发生异常!"+e);
        }
    }
    
    /**
     * @Description:发送Html邮件(收件人,主题,内容都暂时写死)
     * @return
     * @author:hxc
     */
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);   //true表示需要创建一个multipart message
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            System.out.println("html邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("发送html邮件时发生异常!"+e);
        }
    }
    
    public void sendTemplateMail(){
        
    }
    
    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); //可以解析html标签
//            helper.setText(content); // 不能解析html标签
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
            helper.addAttachment(fileName, file);
            System.out.println(fileName);
            //helper.addAttachment("test"+fileName, file);
            mailSender.send(message);
            System.out.println("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            System.out.println("发送带附件的邮件时发生异常!"+e);
        }
    }
}

4.在controller层新加MailController类

package com.bh.controller;
 
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.bh.service.MailService;
 
 
/**
 * @Description:发送邮件的Controller
 * @author hxc
 */
@RestController
@RequestMapping("/mail")
public class MailController {
    
    @Autowired
    private MailService mailService;
    
    @Autowired
    private TemplateEngine templateEngine;
    
    /**
     * @Description:发送简单邮件(收件人,主题,内容都暂时写死)
     * 访问地址:http://localhost:8080/mail/sendSimpleMail
     * @return
     * @author:hxc
     */
    @RequestMapping("/sendSimpleMail")
    public String sendSimpleMail() {
        String to = "[email protected]";
        String subject = "test simple mail";
        String content = "hello, this is simple mail";
        mailService.sendSimpleMail(to, subject, content);
        return "success";
    }
    /**
     * @Description:发送Html格式的邮件(收件人,主题,内容都暂时写死)
     * 访问地址:http://localhost:8080/mail/sendHtmlMail
     * @return
     * @author hxc
     */
    @RequestMapping("/sendHtmlMail")
    public String  sendHtmlMail() {
        String to = "[email protected]";
        String subject = "test html mail";
        String content = "hello, this is html mail";
        mailService.sendHtmlMail(to, subject, content);
        return "success";
    }
    
 
 
    /**
     * @Description:发送带有附件的邮件
     * 访问地址:http://localhost:8080/mail/sendAttachmentsMail
     * @author:hxc
     */
    @Test
    @RequestMapping("/sendAttachmentsMail")
    public String sendAttachmentsMail() {
        String filePath="D:\\课外书籍\\jQuery权威指南.pdf";
//        mailService.sendAttachmentsMail("[email protected]", "主题:带附件的邮件", "有附件,请查收!", filePath);
        return "success";
    }
    
    
    /**
     * @Description:发送模板邮件
     * 访问地址:http://localhost:8080/mail/sendTemplateMail
     * @author:hxc
     */
    @Test
    @RequestMapping("/sendTemplateMail")
    public String sendTemplateMail() {
        //创建邮件正文
        Context context = new Context();
        context.setVariable("user", "zoey");
        context.setVariable("web", "夏梦雪");
        context.setVariable("company", "测试公司");
        context.setVariable("product","梦想产品");
        String emailContent = templateEngine.process("emailTemplate", context);
        mailService.sendHtmlMail("[email protected]","主题:这是模板邮件",emailContent);
        return "sucess";
    }
}

5.在src/main/test/包内添加如下代码:

新建Test1测试类:

代码如下

package test;
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.SpringJUnit4ClassRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.bh.TestApplication;
import com.bh.service.MailService;

@SpringBootTest(classes = TestApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Test1{

    @Autowired
    private MailService mailService;
    
    @Autowired
    private TemplateEngine templateEngine;
    
    @Test
    public void Test2() {
//        mailService.sendSimpleMail("[email protected]","test simple mail","hello, this is simple mail");
          Context context = new Context();
          context.setVariable("user", "zoey");
          context.setVariable("web", "夏梦雪");
          context.setVariable("company", "测试公司");
          context.setVariable("product","梦想产品");
          String emailContent = templateEngine.process("emailTemplate", context);
        mailService.sendAttachmentsMail("[email protected]","成绩单",emailContent,"C:\\Users\\admin\\Desktop\\新建.xls");
        //创建邮件正文
//        Context context = new Context();
//        context.setVariable("user", "zoey");
//        context.setVariable("web", "夏梦雪");
//        context.setVariable("company", "测试公司");
//        context.setVariable("product","梦想产品");
//        String emailContent = templateEngine.process("emailTemplate", context);
//        mailService.sendHtmlMail("[email protected]","激活邮件",emailContent);
    }
}

6.在src/main/resources包下新建templates文件夹,然后创建文件emailTemplate.html

html文件内容如下:

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>Title</title>
    </head>
    <body>
        <p th:text="'尊敬的 ' + ${user} + '用户:'"></p>
                  
        <p th:text=" '恭喜您注册成为'+${web}+'网的用户,同时感谢您对'+${company}+'的关注与支持并欢迎您使用'+${product}+'的产品与服务。'"></p>
        
    </body>
</html>

然后用测试类一一测试,即可发现可以发送简单邮件,也可以发送html邮件,也可以发送模板文件。

猜你喜欢

转载自blog.csdn.net/huxiaochao_6053/article/details/85043826