Spring发送邮件总结(附源码)

简介: Spring发送邮件总结(附源码)

做项目用到自动发邮件功能,网上查阅很多没有给出特别详细的说明,需要自己去探索,做了很多弯路。

在此给大家分享一下自己的代码:

360网盘下载地址:http://yunpan.cn/cJzDQ3gVUHBxY  访问密码 8221

1.png使用时 请将Spring 配置文件里的  用户名、密码、邮箱服务器 还有端口 进行修改如果不是 yeah邮箱。



如果使用maven项目:


Pom.xml



添加的内容


<!-- Spring3 -->

 <dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-core</artifactId>

  <version>3.2.4.RELEASE</version>

 </dependency>

 <dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-context</artifactId>

  <version>3.2.4.RELEASE</version>

 </dependency>

 <dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-jdbc</artifactId>

  <version>3.2.4.RELEASE</version>

 </dependency>

 <dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-web</artifactId>

  <version>3.2.4.RELEASE</version>

 </dependency>

 <dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-aop</artifactId>

  <version>3.2.4.RELEASE</version>

 </dependency>

<!-- Spring Email -->

 <dependency>

     <groupId>org.springframework</groupId>

     <artifactId>spring-context-support</artifactId>

     <version>3.2.4.RELEASE</version>

 </dependency>

 

 <!-- Javamail API -->

   <dependency>

     <groupId>javax.mail</groupId>

     <artifactId>mail</artifactId>

     <version>1.4.4</version>

</dependency>



如果直接导入JAR方式 ,需要引入如下JAR包

20150306000124845.png

ailUtil


package com.bookmarksClouds.util;

import java.io.File;

import javax.annotation.Resource;

import javax.mail.MessagingException;

import javax.mail.internet.MimeMessage;

import org.springframework.core.io.ClassPathResource;

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;

@Component("simpleMail")

public class EmailUtil

{



  private JavaMailSender javaMailSender;

  private SimpleMailMessage simpleMailMessage;

 

  /**

     *

     * @方法名: sendMail

     * @参数名:@param subject 邮件主题

     * @参数名:@param content 邮件主题内容

     * @参数名:@param to        收件人Email地址

     * @param isHtml  是否是html格式(发送html时使用utf-8编码)

     * @描述语:  发送邮件

     * @throws MessagingException 发送发生了异常

     */

    public void sendMail(String subject, String content,boolean isHtml, String to) throws MessagingException

    {

     

     

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();

       

            MimeMessageHelper messageHelper =null;

            if(isHtml)

            {

              messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");

            }

            else

            {

               messageHelper = new MimeMessageHelper(mimeMessage,true);

            }

            messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email

            messageHelper.setSubject(subject); //设置邮件主题

            if(isHtml)

            {

              messageHelper.setText(content,true);   //设置邮件主题内容(html格式)

            }

            else

            {

              messageHelper.setText(content);   //设置邮件主题内容

            }

         

         

            messageHelper.setTo(to);          //设定收件人Email

       

         

            javaMailSender.send(mimeMessage);  

    }

 

 

 

 

 

 

   /**

    * 发送邮件 (包含附件)

    * @param subject 主题

    * @param content 内容

    * @param fileAttachment 附件文件

    * @param isHtml 内容是否是html格式

    * @param to 发送的邮箱地址

    * @throws MessagingException 发送邮件异常(失败)

    */

    public void sendMail(String subject, String content,boolean isHtml, File fileAttachment,String to) throws MessagingException

    {

     

     

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();

       

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");

         

            messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email

            messageHelper.setSubject(subject); //设置邮件主题

            if(isHtml)

            {

              messageHelper.setText(content,true);   //设置邮件主题内容(html格式)

            }

            else

            {

              messageHelper.setText(content);   //设置邮件主题内容

            }

            messageHelper.setTo(to);          //设定收件人Email

            FileSystemResource file = new FileSystemResource(fileAttachment);

       

             messageHelper.addAttachment(file.getFilename(), file); //添加附件

            javaMailSender.send(mimeMessage);  

        }

 

 

 

    /**

     * 发送邮件 (包含附件)

     * @param subject 主题

     * @param content 内容

     * @param classPathResource 附件文件(附加在项目内部时候)

     * @param isHtml 内容是否是html格式

     * @param to 发送的邮箱地址

     * @throws MessagingException

     */

     public void sendMail(String subject, String content,boolean isHtml, ClassPathResource classPathResource,String to)

       throws MessagingException

     {

       

       

             MimeMessage mimeMessage = javaMailSender.createMimeMessage();

           /**

              * new MimeMessageHelper(mimeMessage,true)之true个人见解:

              * 关于true参数,官方文档是这样解释的:

              * use the true flag to indicate you need a multipart message

              * 翻译过来就是:使用true,以表明你需要多个消息

              * 再去翻一下MimeMessageHelper的API,找到这样一句话:

              * supporting alternative texts, inline elements and attachments

              * 也就是说,如果要支持内联元素和附件就必须给定第二个参数为true

              * 否则抛出 java.lang.IllegalStateException 异常

              */

             MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");

             messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email

             messageHelper.setSubject(subject); //设置邮件主题

             if(isHtml)

             {

               messageHelper.setText(content,true);   //设置邮件主题内容(html格式)

             }

             else

             {

               messageHelper.setText(content);   //设置邮件主题内容

             }

             messageHelper.setTo(to);          //设定收件人Email

             /**  FileSystemResource file = new FileSystemResource(fileAttachment);

         

              * ClassPathResource:很明显就是类路径资源,我这里的附件是在项目里的,所以需要用ClassPathResource

              * 如果是系统文件资源就不能用ClassPathResource,而要用FileSystemResource,例:

              *

         

             ClassPathResource file = new ClassPathResource("attachment/Readme.txt");

               */

           /**

              * MimeMessageHelper的addAttachment方法:

              * addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)

              * InputStreamSource是一个接口,ClassPathResource和FileSystemResource都实现了这个接口

           

         

               //发送附件邮件

             */

             ClassPathResource file = classPathResource;

              messageHelper.addAttachment(file.getFilename(), file); //添加附件

             javaMailSender.send(mimeMessage);  

       

     }

   

 

      //Spring 依赖注入

    @Resource

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {

        this.simpleMailMessage = simpleMailMessage;

    }

      //Spring 依赖注入

    @Resource

    public void setJavaMailSender(JavaMailSender javaMailSender) {

        this.javaMailSender = javaMailSender;

    }

}


Demo


package com.bookmarksClouds.test;

import javax.mail.MessagingException;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bookmarksClouds.util.EmailUtil;

public class EmailUtilTest

{

 private  ApplicationContext factory = new ClassPathXmlApplicationContext(

            new String[] {"spring/spring-smtp-mail-attachment.xml"});

@Test

public void test()

{

 

 EmailUtil mail = (EmailUtil)factory.getBean("simpleMail");

 String html= "<html><head><META http-equiv=Content-Type content='text/html; charset=UTF-8'><title>云书签注册激活</title></head><body>欢迎使用,云书签。<br/><a href='www.baidu.com' >云书签</a><br>点击上面超链接 激活账户信息!</body><html>";

 

       try {

  mail.sendMail("云书签注册自动发邮件", html,true, "***@qq.com");

 } catch (MessagingException e) {

  System.out.println("发送邮件失败!");

  //e.printStackTrace();

 }

}

}


Spring配置文件


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns:context="http://www.springframework.org/schema/context"

      xmlns:aop="http://www.springframework.org/schema/aop"

      xsi:schemaLocation="http://www.springframework.org/schema/beans

         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

         http://www.springframework.org/schema/context

         http://www.springframework.org/schema/context/spring-context-3.2.xsd

         http://www.springframework.org/schema/aop

         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

                     <context:annotation-config/>

<context:component-scan base-package="com.bookmarksClouds"/>  

<bean  id ="mailSender"  class ="org.springframework.mail.javamail.JavaMailSenderImpl" >

        <!--  服务器  -->

         <property  name ="host"  value ="smtp.163.com"   />

         <!--  端口号  -->

         <property  name ="port"  value ="25"   />

         <!--  用户名  -->

         <property  name ="username"  value ="邮箱地址"   />

         <!--   密码    -->

         <property  name ="password"  value ="邮箱密码"   />

         <!--  SMTP服务器验证  -->

         <property  name ="javaMailProperties" >

             <props >

                 <!--  验证身份  -->

                <prop  key ="mail.smtp.auth" > true </prop >

            </props >

         </property >

</bean >

<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">

       <!-- 发件人email -->

       <property name="from" value="发送邮箱地址" />

       <!--

        收件人email

       <property name="to" value="to@yeah.net" />

       email主题(标题)

       <property name="subject" value="Subject" />

       email主题内容

       <property name="text">

         <value>ContentText</value>

       </property>

       -->

   </bean>

 

</beans>



////

相关文章
|
19天前
|
Java 应用服务中间件 Nacos
Spring Cloud 常用各个组件详解及实现原理(附加源码+实现逻辑图)
Spring Cloud 常用各个组件详解及实现原理(附加源码+实现逻辑图)
31 0
|
22天前
|
监控 数据可视化 安全
一套成熟的Spring Cloud智慧工地平台源码,自主版权,开箱即用
这是一套基于Spring Cloud的智慧工地管理平台源码,具备自主版权,易于使用。平台运用现代技术如物联网、大数据等改进工地管理,服务包括建设各方,提供人员、车辆、视频监控等七大维度的管理。特色在于可视化管理、智能报警、移动办公和分布计算存储。功能涵盖劳务实名制管理、智能考勤、视频监控AI识别、危大工程监控、环境监测、材料管理和进度管理等,实现工地安全、高效的智慧化管理。
|
1月前
|
消息中间件 NoSQL Java
Spring Cloud项目实战Spring Cloud视频教程 含源码
Spring Cloud项目实战Spring Cloud视频教程 含源码
33 1
|
2月前
|
设计模式 Java Spring
【Spring源码】WebSocket做推送动作的底层实例是谁
我们都知道WebSocket可以主动推送消息给用户,那做推送动作的底层实例究竟是谁?我们先整体看下整个模块的组织机构。可以看到handleMessage方法定义了每个消息格式采用不同的消息处理方法,而这些方法该类并**没有实现**,而是留给了子类去实现。
27 1
【Spring源码】WebSocket做推送动作的底层实例是谁
|
20小时前
|
监控 Java 应用服务中间件
Spring Boot 源码面试知识点
【5月更文挑战第12天】Spring Boot 是一个强大且广泛使用的框架,旨在简化 Spring 应用程序的开发过程。深入了解 Spring Boot 的源码,有助于开发者更好地使用和定制这个框架。以下是一些关键的知识点:
12 6
|
1天前
|
Java 应用服务中间件 测试技术
深入探索Spring Boot Web应用源码及实战应用
【5月更文挑战第11天】本文将详细解析Spring Boot Web应用的源码架构,并通过一个实际案例,展示如何构建一个基于Spring Boot的Web应用。本文旨在帮助读者更好地理解Spring Boot的内部工作机制,以及如何利用这些机制优化自己的Web应用开发。
10 3
|
4天前
|
存储 前端开发 Java
Spring Boot自动装配的源码学习
【4月更文挑战第8天】Spring Boot自动装配是其核心机制之一,其设计目标是在应用程序启动时,自动配置所需的各种组件,使得应用程序的开发和部署变得更加简单和高效。下面是关于Spring Boot自动装配的源码学习知识点及实战。
13 1
|
5天前
|
传感器 人工智能 前端开发
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
智慧校园电子班牌,坐落于班级的门口,适合于各类型学校的场景应用,班级学校日常内容更新可由班级自行管理,也可由学校统一管理。让我们一起看看,电子班牌有哪些功能呢?
47 4
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
|
12天前
|
Java API 数据安全/隐私保护
【亮剑】如何在Java项目中结合Spring框架实现邮件发送功能
【4月更文挑战第30天】本文介绍了如何在Java项目中结合Spring框架实现邮件发送功能。首先,需在`pom.xml`添加Spring和JavaMail依赖。然后,在`applicationContext.xml`配置邮件发送器,包括SMTP服务器信息。接着,创建一个使用依赖注入的`EmailService`类,通过`JavaMailSender`发送邮件。最后,调用`EmailService`的`sendSimpleEmail`方法即可发送邮件。最佳实践包括:使用配置管理敏感信息,利用`MimeMessage`构造复杂邮件,异常处理和日志记录,以及在大量发送时考虑使用邮件队列。
|
13天前
|
设计模式 安全 Java
【初学者慎入】Spring源码中的16种设计模式实现
以上是威哥给大家整理了16种常见的设计模式在 Spring 源码中的运用,学习 Spring 源码成为了 Java 程序员的标配,你还知道Spring 中哪些源码中运用了设计模式,欢迎留言与威哥交流。