Spring Cloud 2.x系列之springboot发送邮件

简介: 虽然现在短信验证已经最流行也是最常用的验证方式;但是邮件验证还是必不可少,依然是网站的必备功能之一。什么注册验证,忘记密码或者是给用户发送营销信息都是可以使用邮件发送功能的。最早期使用JavaMail的相关api来进行发送邮件的功能开发,后来spring整合了JavaMail的相关api推出了JavaMailSender更加简化了邮件发送的代码编写,现在springboot对此进行了封装就有了现在的spring-boot-starter-mail。

虽然现在短信验证已经最流行也是最常用的验证方式;但是邮件验证还是必不可少,依然是网站的必备功能之一。什么注册验证,忘记密码或者是给用户发送营销信息都是可以使用邮件发送功能的。最早期使用JavaMail的相关api来进行发送邮件的功能开发,后来spring整合了JavaMail的相关api推出了JavaMailSender更加简化了邮件发送的代码编写,现在springboot对此进行了封装就有了现在的spring-boot-starter-mail。

1、新建项目sc-mail,对应的pom.xml文件如下

<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>


   <groupId>spring-cloud</groupId>

   <artifactId>sc-mail</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>jar</packaging>


   <name>sc-mail</name>

   <url>http://maven.apache.org</url>

   <parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>2.0.4.RELEASE</version>

   </parent>

   <dependencyManagement>

      <dependencies>

        <dependency>

           <groupId>org.springframework.cloud</groupId>

           <artifactId>spring-cloud-dependencies</artifactId>

           <version>Finchley.RELEASE</version>

           <type>pom</type>

           <scope>import</scope>

        </dependency>


      </dependencies>

   </dependencyManagement>



   <properties>

      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

      <maven.compiler.source>1.8</maven.compiler.source>

      <maven.compiler.target>1.8</maven.compiler.target>

   </properties>

   <dependencies>


      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-mail</artifactId>

      </dependency>


      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

      </dependency>

   </dependencies>

</project>

2、新建配置文件application.yml

spring:

  application:

    name: sc-mail

  mail:

    host: smtp.qq.com #邮箱服务器地址

    port: 465

    username:515768476@qq.com #用户名

    password: vfcqhwsnnwugbhcx#密码(改成自己的密码)

    default-encoding: UTF-8

    properties:

      mail:

        smtp:

          ssl:

            enable:

              true

注意配置:

spring.mail.properties.mail.smtp.ssl.enable=true

否则可能如何如下错误:

https://blog.csdn.net/u013360850/article/details/78824366

3、新建邮件发送服务类

package sc.mail.service.impl;


import java.io.File;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

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;



import sc.mail.service.MailService;



@Service

public class MailServiceImpl implements MailService {



   privatefinal Logger logger =LoggerFactory.getLogger(this.getClass());



   @Autowired
   private JavaMailSender mailSender;



   /**

    * 文本

    * @param from

    * @param to

    * @param subject

    * @param content

    */

   @Override

   public void sendSimpleMail(String from, String to, String subject, String content) {

      SimpleMailMessage message = newSimpleMailMessage();

      message.setFrom(from);

      message.setTo(to);

      message.setSubject(subject);

      message.setText(content);

      try {

        mailSender.send(message);

        logger.info("simple mail had send。");

      } catch (Exception e) {

        logger.error("send mail error", e);

      }

   }



   /**

    * @param from

    * @param to

    * @param subject

    * @param content

    */

   public void sendTemplateMail(String from, String to, String subject, String content) {

       MimeMessage message = mailSender.createMimeMessage();

       try {

           //true表示需要创建一个multipart message

           MimeMessageHelper helper = newMimeMessageHelper(message, true);

           helper.setFrom(from);

           helper.setTo(to);

           helper.setSubject(subject);

           helper.setText(content, true);

           mailSender.send(message);

           logger.info("send template success");

       } catch (Exception e) {

           logger.error("send template eror", e);

       }

   }



   /**

    * 附件

    *

    * @param from

    * @param to

    * @param subject

    * @param content

    * @param filePath

    */

   public void sendAttachmentsMail(String from, String to, String subject, String content, String filePath){

       MimeMessage message = mailSender.createMimeMessage();

       try {

           MimeMessageHelper helper = newMimeMessageHelper(message, true);

           helper.setFrom(from);

           helper.setTo(to);

           helper.setSubject(subject);

           helper.setText(content, true);

           FileSystemResource file = newFileSystemResource(new File(filePath));

           String fileName = filePath.substring(filePath.lastIndexOf(File.separator));

           helper.addAttachment(fileName, file);

           mailSender.send(message);

           logger.info("send mail with attach success。");

       } catch (Exception e) {

           logger.error("send mail with attach success", e);

       }

   }



   /**

    * 发送内嵌图片

    *

    * @param from

    * @param to

    * @param subject

    * @param content

    * @param imgPath

    * @param imgId

    */

   public void sendInlineResourceMail(String from, String to, String subject, String content,

        String imgPath, String imgId){

       MimeMessage message = mailSender.createMimeMessage();

       try {

           MimeMessageHelper helper = newMimeMessageHelper(message, true);

           helper.setFrom(from);

           helper.setTo(to);

           helper.setSubject(subject);

           helper.setText(content, true);

           FileSystemResource res = newFileSystemResource(new File(imgPath));

           helper.addInline(imgId, res);

           mailSender.send(message);

           logger.info("send inner resources success。");

       } catch (Exception e) {

           logger.error("send inner resources fail", e);

       }

   }


}    

4、新建测试类

package sc.mail;

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


@RunWith(SpringRunner.class)

@SpringBootTest

public class MailSendTest {


   @Autowired

   privateMailService mailService;


   @Test

   public void sendSimpleMailTest() {

      mailService.sendSimpleMail("515768476@qq.com", "happy.huangjinjin@163.com",

           "sendSimpleMailTest", "sendSimpleMailTestfrom 515768476@qq.com");

   }



   @Test

   public void sendTemplateMailTest() {

      String html = "<html><body>"

           + " <div> "

           + "   sendTemplateMailTest from 515768476@qq.com </br>"

           + "   <b>这是模板邮件</b>"

           + "</div>"

           + "</body></html>";

      mailService.sendTemplateMail("515768476@qq.com", "happy.huangjinjin@163.com",

           "sendTemplateMailTest", html);

   }



   @Test

   public void sendAttachmentsMailTest() {

      String filePath = "D:\\springcloudws\\sc-mail\\src\\main\\java\\sc\\mail\\service\\impl\\MailServiceImpl.java";

      mailService.sendAttachmentsMail("515768476@qq.com", "happy.huangjinjin@163.com",

           "sendAttachmentsMailTest", "sendAttachmentsMailTestfrom 515768476@qq.com", filePath);

   }



   @Test

   public voidsend InlineResourceMailTest() {

      String imgId = "img1";



      String content = "<html><body>"

           + "sendInlineResourceMailTest:<img src=\'cid:" + imgId + "\'>"

                 + "</body></html>";



      String imgPath = "D:\\springcloudws\\sc-mail\\src\\main\\resources\\20181015223228.jpg";



      mailService.sendInlineResourceMail("515768476@qq.com", "happy.huangjinjin@163.com",

           "sendAttachmentsMailTest", content, imgPath, imgId);

   }



}

5、运行测试类验证是否发送邮件成功

登录happy.huangjinjin@163.com邮箱

e3cf98de6ce30bac8e07d81de3c4559aae938cd4

简单邮件

c712da63ba6bd40baea7a8cd307822166ca394a2

模板邮件

17e3e2d342b56b0b2a713f3c493d62646effd9c2

附件邮件

fbeabe02f417af49f0fe8a5d48657e23ce517cc9

内嵌图片邮件

6480623732edce59423745a5727e9af8e5a60a27

源码:

https://gitee.com/hjj520/spring-cloud-2.x/tree/master/sc-mail

c7690fcdaea6b8f3f71e08dfc844ef8371aad1f6

本文作者: java乐园

本文来自云栖社区合作伙伴“JAVA乐园”,了解相关信息可以关注“JAVA乐园

相关文章
|
22天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
38 0
|
30天前
|
负载均衡 Java API
Spring Cloud 面试题及答案整理,最新面试题
Spring Cloud 面试题及答案整理,最新面试题
132 1
|
11天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
30天前
|
Java Nacos Sentinel
Spring Cloud Alibaba 面试题及答案整理,最新面试题
Spring Cloud Alibaba 面试题及答案整理,最新面试题
138 0
|
1月前
|
SpringCloudAlibaba Java 持续交付
【构建一套Spring Cloud项目的大概步骤】&【Springcloud Alibaba微服务分布式架构学习资料】
【构建一套Spring Cloud项目的大概步骤】&【Springcloud Alibaba微服务分布式架构学习资料】
131 0
|
1天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
4 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
2天前
|
负载均衡 Java 开发者
细解微服务架构实践:如何使用Spring Cloud进行Java微服务治理
【4月更文挑战第17天】Spring Cloud是Java微服务治理的首选框架,整合了Eureka(服务发现)、Ribbon(客户端负载均衡)、Hystrix(熔断器)、Zuul(API网关)和Config Server(配置中心)。通过Eureka实现服务注册与发现,Ribbon提供负载均衡,Hystrix实现熔断保护,Zuul作为API网关,Config Server集中管理配置。理解并运用Spring Cloud进行微服务治理是现代Java开发者的关键技能。
|
3天前
|
Java API 对象存储
对象存储OSS产品常见问题之使用Spring Cloud Alibaba情况下文档添加水印如何解决
对象存储OSS是基于互联网的数据存储服务模式,让用户可以安全、可靠地存储大量非结构化数据,如图片、音频、视频、文档等任意类型文件,并通过简单的基于HTTP/HTTPS协议的RESTful API接口进行访问和管理。本帖梳理了用户在实际使用中可能遇到的各种常见问题,涵盖了基础操作、性能优化、安全设置、费用管理、数据备份与恢复、跨区域同步、API接口调用等多个方面。
22 2
|
3天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
28 0
【Spring系列】Sping VS Sping Boot区别与联系
|
11天前
|
Java 容器
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
12 0