五.SpringBoot集成实例系列-邮件email文章列表

版权声明:本文为博主原创文章,转载请注明原地址 https://blog.csdn.net/a123demi/article/details/76339163
文章列表

本系列将通过实例分别实现Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket。
具体文章系列如下:
一.SpringBoot集成实例系列-xml型单数据源mybatis
二.SpringBoot集成实例系列-xml型多数据源mybatis
三.SpringBoot集成实例系列-注解型单数据源mybatis
四.SpringBoot集成实例系列-注解型多数据源mybatis
五.SpringBoot集成实例系列-邮件email
六.SpringBoot集成实例系列-单数据源mongodb
七.SpringBoot集成实例系列-多数据源mongodb
八.SpringBoot集成实例系列-缓存redis
九.SpringBoot集成实例系列-数据库cassandra
十.SpringBoot集成实例系列-定时任务scheduler
十一.SpringBoot集成实例系列-消息队列kafka
十二.SpringBoot集成实例系列-消息推送websocket

前几篇文章,小求带简单的实现了springBoot集成mybatis的实例。众所周知,Email在我们的生活和工作中发挥巨大作用,如应用需要邮箱验证、异常问题邮箱通知等。本篇文件我们将通过实例介绍springboot集成email。

1.需求

实例需要实现email发送普通文本、附件和图片资源等功能。

2.技术要点

2.1 pom关键依赖

<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
		</dependency>

		<!-- 模板引擎 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

2.2 配置文件

#SMTP server host. For instance `smtp.example.com`
spring.mail.host=smtp.163.com
#Login user of the SMTP server
spring.mail.username=email_test_123@163.com
#Login password of the SMTP server
#此处为客户端授权密码EMAIL123
spring.mail.password=EMAIL123
#Default MimeMessage encoding
spring.mail.default-encoding=UTF-8
springboot配置详情见本人博客:http://blog.csdn.net/a123demi/article/details/73917802
客户端授权密码设置:

2.3 关键实现


JavaMailSender:
用于JavaMail的扩展MailSender接口,支持MIME消息作为直接参数和准备回调。通常与MimeMessageHelper类一起使用,方便创建JavaMail MimeMessages,包括附件等。

SimpleMailMessage:支持普通文本消息
MimeMessage:支持Mime类消息,与MimeMessageHelper一起使用

3.代码实现

3.1 项目结构


3.2 邮件接口

package com.lm.service;

public interface MailService {
	/**
	 * 发送普通邮件
	 * @param to
	 * @param subject
	 * @param content
	 */
	public void sendSimpleMail(String to, String subject, String content);
	
	/**
	 * 发送html格式邮件
	 * @param to
	 * @param subject
	 * @param content
	 */
	public void sendHtmlMail(String to, String subject, String content);

	/**
	 * 发送带附件邮件
	 * @param to
	 * @param subject
	 * @param content
	 * @param filePath
	 */
	public void sendAttachmentsMail(String to, String subject, String content, String filePath);

	/**
	 * 发送正文中有静态资源(图片)的邮件
	 * @param to
	 * @param subject
	 * @param content
	 * @param rscPath
	 * @param rscId
	 */
	public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);
}

3.3 邮件接口实现

package com.lm.service.impl;

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

import com.lm.service.MailService;

/**
 * 邮件实现类
 * @author liangming.deng
 * @date   2017年7月29日
 *
 */
@Component
public class MailServiceImpl implements MailService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

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

    /**
     * 发送文本邮件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    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
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart 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 (MessagingException e) {
            logger.error("发送html邮件时发生异常!", e);
        }
    }


    /**
     * 发送带附件的邮件
     * @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);

            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);
        }
    }


    /**
     * 发送正文中有静态资源(图片)的邮件
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
        MimeMessage message = mailSender.createMimeMessage();

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

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }
}

3.4 测试用例

package com.lm;

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.lm.service.MailService;

/**
 * 
 * @author liangming.deng
 * @date   2017年7月29日
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testSimpleMail() throws Exception {
        mailService.sendSimpleMail("email_test_123@163.com","test simple mail"," hello this is simple mail");
    }

    @Test
    public void testHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail("email_test_123@163.com","test simple mail",content);
    }

    @Test
    public void sendAttachmentsMail() {
        String filePath="d:\\tmp\\iot-springboot.log";
        mailService.sendAttachmentsMail("email_test_123@163.com", "主题:带附件的邮件", "有附件,请查收!", filePath);
    }


    @Test
    public void sendInlineResourceMail() {
        String rscId = "test006";
        String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "D:\\01.jpg";

        mailService.sendInlineResourceMail("email_test_123@163.com", "主题:这是有图片的邮件", content, imgPath, rscId);
    }


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

        mailService.sendHtmlMail("email_test_123@163.com","主题:这是模板邮件",emailContent);
    }
}

3.5 实现效果


4.代码地址

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