天天看點

Spring發送郵件總結(附源碼)

做項目用到自動發郵件功能,網上查閱很多沒有給出特别詳細的說明,需要自己去探索,做了很多彎路。

在此給大家分享一下自己的代碼:

360網盤下載下傳位址:

http://yunpan.cn/cJzDQ3gVUHBxY

  通路密碼 8221

Spring發送郵件總結(附源碼)

使用時 請将Spring 配置檔案裡的  使用者名、密碼、郵箱伺服器 還有端口 進行修改如果不是 yeah郵箱。

如果使用maven項目:

Pom.xml

添加的内容

<!-- Spring3 -->

 <dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-core</artifactId>

  <version>3.2.4.RELEASE</version>

 </dependency>

  <artifactId>spring-context</artifactId>

  <artifactId>spring-jdbc</artifactId>

  <artifactId>spring-web</artifactId>

  <artifactId>spring-aop</artifactId>

<!-- Spring Email -->

     <groupId>org.springframework</groupId>

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

     <version>3.2.4.RELEASE</version>

 <!-- Javamail API -->

   <dependency>

     <groupId>javax.mail</groupId>

     <artifactId>mail</artifactId>

     <version>1.4.4</version>

</dependency>

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

Spring發送郵件總結(附源碼)

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); //設定郵件主題

              messageHelper.setText(content,true);   //設定郵件主題内容(html格式)

              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

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

            FileSystemResource file = new FileSystemResource(fileAttachment);

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

        }

    /**

     * 發送郵件 (包含附件)

     * @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;

    public void setJavaMailSender(JavaMailSender javaMailSender) {

        this.javaMailSender = javaMailSender;

}

Demo

package com.bookmarksClouds.test;

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="[email protected]" />

       email主題(标題)

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

       email主題内容

       <property name="text">

         <value>ContentText</value>

       </property>

       -->

   </bean>

</beans>