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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Caide3/article/details/79978326

最近在学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(十):邮件服务
阅读更多

扫码向博主提问

laughitover

非学,无以致疑;非问,无以广识
去开通我的Chat快问
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页