使用spring boot 实现发送邮件总结

原创 2018年04月17日 18:13:27

最近在学sprin boot,总结一个发送邮件方法:可以发送普通邮件,带附件(可以是多个),带静态资源,使用模板的邮件

难点:使用thymeleaf读取配置文件中的中文

1.编写pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>demo3</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo3</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<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>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

2.编写application.properties

spring.mail.host=邮件服务器地址
spring.mail.username=用户名
spring.mail.password=密码
spring.mail.default-encoding=UTF-8
mail.fromMail.addr=发件人
#spring.messages.basename=messages

3.实现类:

package com.example.demo3.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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.File;


/**
 * Created by jueye on 2018/4/16.
 */
@Component
public class MailServiceImpl{
    private final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String from;

    /**
     * 发送简单邮件
     * @param to
     * @param subject
     * @param content
     */
    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);
            logger.info("简单邮件已发送.");
        }catch (Exception e){
            logger.error("发送邮件异常:",e);
        }
    }

    /**
     * 发送html格式邮件(也可以发送普通邮件)
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String to,String subject,String content){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true message
            MimeMessageHelper helper =new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);

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

    }

    /**
     * 发送可以带多个附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePathArr
     */

    public void sendAttachmentMail(String to,String subject,String content,String []filePathArr){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);

            int arrLength=filePathArr.length;
            if(arrLength>0){
                for(int i=0;i<arrLength;i++){
                    String filePath=filePathArr[i];
                    File file=new File(filePath);
                    FileSystemResource fileRes = new FileSystemResource(file);
                    String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
                    helper.addAttachment(fileName,fileRes);
                }
            }else{
                logger.info("邮件没有附件!");
            }

            mailSender.send(message);
            logger.info("发送带附件邮件成功!");
        } catch (Exception e) {
            logger.error("发送带附件邮件异常",e);
        }
    }

    /**
     * 发送带静态资源的邮件(可以是多个静态资源)
     * @param to
     * @param subject
     * @param content
     * @param resPath
     * @param resId
     */
    public void sendInlineResourceMail(String to,String subject,String content,
                                       String resPath[],String resId[]){
        MimeMessage message =mailSender.createMimeMessage();

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

            int length=resPath.length;
            if(length>0){
                for (int i=0;i<length;i++){
                    FileSystemResource res = new FileSystemResource(resPath[i]);
                    helper.addInline(resId[i],res);
                }
            }else{
                logger.info("没有静态资源!");
            }

            mailSender.send(message);
            logger.info("发送带静态资源的邮件成功!");
        }catch (Exception e){
            logger.error("发送静态资源邮件异常:",e);
        }

    }

    /**
     * 发送邮件统一方法(可以是简单邮件,可以带附件,可以有静态资源,可以是模板)
     * @param to
     * @param subject
     * @param content
     * @param attachPathArr
     * @param resPath
     * @param resId
     */
    public void sendMail(String to,String subject,String content,String []attachPathArr,
                                       String resPath[],String resId[]){
        MimeMessage message =mailSender.createMimeMessage();

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


            int arrLength=attachPathArr.length;
            if(arrLength>0){
                for(int i=0;i<arrLength;i++){
                    String filePath=attachPathArr[i];
                    File file=new File(filePath);
                    FileSystemResource fileRes = new FileSystemResource(file);
                    String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
                    helper.addAttachment(fileName,fileRes);
                }
            }else{
                logger.info("邮件没有附件!");
            }

            int length=resPath.length;
            if(length>0){
                for (int i=0;i<length;i++){
                    FileSystemResource res = new FileSystemResource(resPath[i]);
                    helper.addInline(resId[i],res);
                }
            }else{
                logger.info("没有静态资源!");
            }

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

    }
}

4.在resources/templates下新建模板emailTemplate.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
        PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<br xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Title</title>
</head>
<br>
    from:<span th:text="#{welcome}"></span><br>
    您好,<span th:text="*{name}"></span>,id:<span th:text="${id}">:</span><br>
    这是测试邮件,如有问题,请点击下面的链接
    <a href="#" th:href="@{ http://www.huisheng.com/{id}(id=${id}) }">带参数</a>
</body>
</html>

5.在resources下创建messages.properties

welcome =欢迎你登录form1.cn

6.在resources下创建messages_zh_CN.properties

welcome =\u6b22\u8fce\u4f60\u767b\u5f55form1.cn

7.测试类

package com.example.demo3;

import com.example.demo3.service.MailServiceImpl;
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 java.io.File;

/**
 * Created by jueye on 2018/4/16.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailServiceImpl mailService;
    @Autowired
    private TemplateEngine templateEngine;

  /*  @Test
    public void testSimpleMail(){
        mailService.sendSimpleMail("wangjs@channelsoft.com","test simple mail", "this is simple mail");
    }

    @Test
    public void testHtmlMail(){
        String content="<html><body>" +
                "<font color='red'>hello world!这是一封html邮件</font>" +
                "</body></html>";
        String content="这是一封html邮件!";
        mailService.sendHtmlMail("wangjs@channelsoft.com","html mail",content);
    }



    @Test
    public void testAttachmentsMail(){
        String filePath="F:"+ File.separator+"temp"+File.separator+"jfind.jar";
        String filePath2="F:"+ File.separator+"temp"+File.separator+"001.jpg";
        String filePath3="F:"+ File.separator+"temp"+File.separator+"002.jpg";
        String []filePathArr={};
//        String []filePathArr={filePath,filePath2,filePath3};
//        filePathArr[0]=filePath;
        String content="<html><body>" +
                "<font color='red'>hello world!这是一封html邮件</font>" +
                "</body></html>";
        mailService.sendAttachmentMail("wangjs@channelsoft.com","带附件的邮件",content,filePathArr);
    }
 */

    @Test
    public void testInlineResMail(){
        //创建邮件正文
        Context context=new Context();
        context.setVariable("name","jueye");
        context.setVariable("id","006");
        String emailContent = templateEngine.process("emailTemplate",context);

        String filePath="F:"+ File.separator+"temp"+File.separator+"jfind.jar";
        String filePath2="F:"+ File.separator+"temp"+File.separator+"001.jpg";
        String filePath3="F:"+ File.separator+"temp"+File.separator+"002.jpg";
        String []filePathArr={filePath,filePath2,filePath3};

        String resId[]={"flash001","flash002"};
        String content="<html><body>" +
                "<font color='red'>hello world!这是一封有图片的邮件:</font>" +
                "<img src=\'cid:"+resId[0]+"\'>"+
                "<img src=\'cid:"+resId[1]+"\'>"+
                "</body></html>";
        String imsPath[]={"F:\\temp\\001.jpg","F:\\temp\\002.jpg"};
        String strArr[]={};
        mailService.sendMail("wangjs@channelsoft.com","终极邮件简版",emailContent,strArr,strArr,strArr);
//        mailService.sendMail("wangjs@channelsoft.com","终极邮件",content,filePathArr,imsPath,resId);

    }

   /* @Test
    public void sendTemplateMail(){
        //创建邮件正文
        Context context=new Context();
        context.setVariable("name","jueye");
        context.setVariable("id","006");
        String emailContent = templateEngine.process("emailTemplate",context);
        mailService.sendHtmlMail("wangjs@channelsoft.com","这是模板文件",emailContent);
    }*/

}
参考文章:springboot(十):邮件服务
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Caide3/article/details/79978326

如何使用Spring Boot/Spring Cloud 实现微服务应用

-
  • 1970年01月01日 08:00

spring boot 实际应用(三)发送邮件实现

这次因为项目需要所以整合了下RabbitMQ 和Mail的发送,所有实现都基于spring boot  加入所依赖的jar  spring-boot-starter-amqp spring-b...
  • luqiang81191293
  • luqiang81191293
  • 2017-01-20 10:43:45
  • 1777

Spring Boot 发送邮件

在 Spring Boot 中使用 Spring Mail 发送邮件 添加 Spring Mail 依赖 build.gradle compile('org.springframework.b...
  • u013360850
  • u013360850
  • 2017-12-16 23:09:33
  • 991

SpringBoot使用FreeMarker模板发送邮件

SpringBoot +Mail+FreeMarker通过spirngboot 自带的mail服务及FreeMarker模板引擎,发送邮 添加依赖 org.springframework.bo...
  • system_linux
  • system_linux
  • 2017-12-13 15:00:05
  • 623

SpringBoot之发送邮件功能

友情提示:一切准备就绪后,如果后台报 javax.mail.AuthenticationFailedException: 535 Error: authentication failed 错误,...
  • w405722907
  • w405722907
  • 2017-08-16 09:04:46
  • 404

springboot发送邮件的实现例子

springboot是集大成者,对于发送邮件的功能也不例外。而且往往是原来的功能实现更简单,方便。更符合Facade Pattern。 下面就是springboot发送邮件的实现例子,代码已封装好,按...
  • mingliangniwo
  • mingliangniwo
  • 2017-02-10 17:00:35
  • 4135

Spring Boot实战之发送邮件

Spring Boot实战之发送邮件 一、邮件服务简介 邮件服务在互联网早期就已经出现,如今已成为人们互联网生活中必不可少的一项服务。那么邮件服务是怎么工作的呢?如下给出邮件发送与接收的典型过程: 1...
  • sun_t89
  • sun_t89
  • 2016-08-10 11:22:39
  • 9358

Springboot集成quartz之定时向用户发送邮件(第二期)

Springboot集成quartz之定时向用户发送邮件(第二期)本期使用邮件发送的功能来验证springboot集成定时任务1. 创建表t_b_email_messageCREATE TABLE `...
  • musuny
  • musuny
  • 2017-07-22 21:51:37
  • 1282

spring boot 学习(十)SpringBoot配置发送Email

SpringBoot配置发送Email
  • u011244202
  • u011244202
  • 2017-02-01 17:30:36
  • 15680

Spring Boot 使用465端口发送邮件

最近做的一个项目中有个邮件发送功能,发送邮件默认是25端口,但是公司用的服务器是阿里云的,会屏蔽25端口,所以部署到服务器后连接不上邮件服务器,需要使用SSL协议(使用465端口)。      需要注...
  • LDY1016
  • LDY1016
  • 2017-10-27 15:04:24
  • 1217
收藏助手
不良信息举报
您举报文章:使用spring boot 实现发送邮件总结
举报原因:
原因补充:

(最多只允许输入30个字)