1. 程式人生 > >使用spring框架中的元件傳送郵件的詳細說明

使用spring框架中的元件傳送郵件的詳細說明

原創作者:http://blog.csdn.net/caimengyuan/article/details/51224269

在進行專案開發的時候,要做一個通過傳送郵件驗證碼的功能來找回密碼。spring傳送郵件的過程這篇部落格寫的太好了。

首先進入自己的QQ郵箱,在設定中修改賬戶資訊

開啟郵箱設定

然後來至底部
開啟SMTP服務

點選開啟,再用手機發送對應資訊到指定號碼,然後點選我已傳送
傳送開通簡訊

獲取授權碼
獲取授權碼
注意提示:授權碼

到這裡,相信你已經開通了SMTP服務,這樣就可以在java code傳送郵件了

接下來的是Spring 中使用郵件服務

首先是配置資訊使用的是587埠,剛開始用465埠我糾結了好久(使用465埠的錯誤詳情),用不了,你可以嘗試,預設的25

埠應該也是不適合的

    <!-- 郵件服務 -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.qq.com"/>
        <property name="port" value="587"/>//或許你可以用465埠,預設的25不適合
        <property name="protocol" value="smtp"
/>
<property name="username" value="[email protected]"/> <property name="password" value="xxxxxxxxxxxx"/>//這裡的是你通過簡訊後,獲取的授權碼 <property name="defaultEncoding" value="UTF-8"/> <property name="javaMailProperties"> <props> <prop
key="mail.smtp.auth">
true</prop> <prop key="mail.smtp.timeout">25000</prop> </props> </property> </bean> <!-- this is a template message that we can pre-load with default state --> <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from" value="[email protected]"/> <property name="subject" value="嘗試發郵件"/> </bean> <bean id="orderManager" class="cn.cherish.common.SimpleOrderManager"> <property name="mailSender" ref="mailSender"/> <property name="templateMessage" ref="templateMessage"/> </bean>

用maven引入的jar包

    <!-- 郵件 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>

下面只是一個工具類作簡單例子,請勿見怪

package cn.cherish.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 專案名稱:springmvc_hibernate
 * 類名稱:MailUtil
 * 類描述:
 * 建立人:Cherish
 * 聯絡方式:[email protected]
 * 建立時間:2016年4月22日 下午3:51:48
 * @version 1.0
 */
public class MailUtil {

    private static final String HOST = "smtp.qq.com";
    private static final String SMTP = "smtp";
    private static final String USERNAME = "[email protected]";
    private static final String PASSWORD = "xxxxxxxxxx";
    private static final int PORT = 587;//587/465
    private static final String DEFAULTENCODING = "UTF-8";

    private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

    private static Properties prop = new Properties();

    static{
        // 設定mail server
        senderImpl.setHost(HOST);
        senderImpl.setProtocol(SMTP);
        senderImpl.setUsername(USERNAME);
        senderImpl.setPassword(PASSWORD);
        senderImpl.setPort(PORT);
        senderImpl.setDefaultEncoding(DEFAULTENCODING);

        // 設定properties
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", "25000");
        //設定除錯模式可以在控制檯檢視傳送過程
        prop.put("mail.debug", "true");

        senderImpl.setJavaMailProperties(prop);
    }

    public static void main(String args[]) {
        // 設定收件人,寄件人 用陣列傳送多個郵件
//      String[] array = new String[] {"[email protected]","[email protected]","[email protected]",USERNAME};
        String[] array = new String[] {USERNAME};
        String subject = "Cherish內嵌圖片、音樂的郵件";

//      StringBuffer sb = new StringBuffer();
//      try {
//          URL url = new URL("http://www.imooc.com/");//http://android-studio.org/
//          
//          URLConnection conn = url.openConnection();
//          InputStream is = conn.getInputStream();
//          
//          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//          
//          String string = null;
//          while ((string = reader.readLine()) != null) {
//              sb.append(string);
//          }
//          
//          //System.out.println(sb.toString());
//          
//      } catch (Exception e) {
//          e.printStackTrace();
//      }
//      
//      boolean result = htmlMail(array, subject, sb.toString());

        String filePath = "E:/javaxmail.png";
        String html = "<html><head>"+
                    "</head><body>"+
                    "<audio src='http://m10.music.126.net/20160422225433/25b43b999bcdaf3425b9194514340596/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3' autoplay='autoplay' controls='controls' loop='-1'>愛你</audio>"+
                    "<h1>Hello,Nice to meet you!</h1>"+
                    "<span style='color:red;font-size:36px;'>並摸了一把你的小奶</span>"+
                    "<img src='cid:javaxmail.png'>"+
                    "</body></html>";
        boolean result = inlineFileMail(array, subject, html, filePath);

        if (result) {
            System.out.println("傳送郵件成功。。。。");
        }


    }

    /**
     * 傳送簡單郵件
     * @param to 收件人郵箱
     * @param subject 主題
     * @param content 內容
     * @return
     */
    public static boolean singleMail(String to, String subject, String content){
        String[] array = new String[] {to};
        return singleMail(array, subject, content);
    }


    /**
     * 傳送簡單文字郵件
     * @param to 收件人郵箱陣列
     * @param subject 主題
     * @param content 內容
     * @return
     */
    public static boolean singleMail(String[] to, String subject, String content){
        boolean result = true;

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 設定收件人,寄件人 用陣列傳送多個郵件
        mailMessage.setTo(to);
        mailMessage.setFrom(USERNAME);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        // 傳送郵件
        try {
            senderImpl.send(mailMessage);
        } catch (MailException e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }


    /**
     * 傳送html郵件
     * @param to 收件人
     * @param subject 主題
     * @param html html程式碼
     * @return
     */
    public static boolean htmlMail(String[] to, String subject, String html){
        boolean result = true;

        MimeMessage mailMessage = senderImpl.createMimeMessage();  
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);  

        try {
            // 設定收件人,寄件人 用陣列傳送多個郵件
            messageHelper.setTo(to);
            messageHelper.setFrom(USERNAME);
            messageHelper.setSubject(subject);
            // true 表示啟動HTML格式的郵件  
            messageHelper.setText(html, true);  

            // 傳送郵件
            senderImpl.send(mailMessage);
        } catch (MessagingException e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 傳送內嵌圖片的郵件   (cid:資源名)
     * @param to 收件人郵箱
     * @param subject 主題
     * @param html html程式碼
     * @param imgPath 圖片路徑
     * @return
     */
    public static boolean inlineFileMail(String[] to, String subject, String html, String filePath){
        boolean result = true;

        MimeMessage mailMessage = senderImpl.createMimeMessage();  
        try {
            //設定true開啟嵌入圖片的功能
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);  
            // 設定收件人,寄件人 用陣列傳送多個郵件
            messageHelper.setTo(to);
            messageHelper.setFrom(USERNAME);
            messageHelper.setSubject(subject);
            // true 表示啟動HTML格式的郵件  
            messageHelper.setText(html, true);  

            FileSystemResource file = new FileSystemResource(new File(filePath));  
            messageHelper.addInline(file.getFilename(), file);  

            // 傳送郵件
            senderImpl.send(mailMessage);
        } catch (MessagingException e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 傳送帶附件的郵件
     * @param to
     * @param subject
     * @param html
     * @param filePath
     * @return
     */
    public static boolean attachedFileMail(String[] to, String subject, String html, String filePath){
        boolean result = true;

        MimeMessage mailMessage = senderImpl.createMimeMessage();  

        try {
            // multipart模式 為true時傳送附件 可以設定html格式
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");  
            // 設定收件人,寄件人 用陣列傳送多個郵件
            messageHelper.setTo(to);
            messageHelper.setFrom(USERNAME);
            messageHelper.setSubject(subject);
            // true 表示啟動HTML格式的郵件  
            messageHelper.setText(html, true);  

            FileSystemResource file = new FileSystemResource(new File(filePath));  
            // 這裡的方法呼叫和插入圖片是不同的。  
            messageHelper.addAttachment(file.getFilename(), file);

            // 傳送郵件
            senderImpl.send(mailMessage);
        } catch (MessagingException e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }



溫馨提示:

<img src='cid:javaxmail.png'>
這是內嵌圖片的方式 javaxmail.png 要和 messageHelper.addInline(file.getFilename(), file); 這裡的 file.getFilename() 相一致就可以

現在只差一步了,那就是Ctrl + F11,有不當之處敬請提出,共同進步
這裡寫圖片描述

**

使用javax.mail發郵件程式碼

**

package cn.cherish.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 專案名稱:springmvc_hibernate 
 * 類名稱:EmailUtil 
 * 類描述:傳送郵件工具類 
 * 建立人:Cherish
 * 聯絡方式:[email protected] 
 * 建立時間:2016年4月23日 上午9:48:21
 * @version 1.0
 */
public class EmailUtil {

    // properties配置檔案地址
    //private static final String PROPERTIES_PATH = "standard_data.properties";

    private static Session session;
    private static Properties props = new Properties();
    private static final String HOST = "smtp.qq.com";
    private static int PORT = 587;
    private static final String isAUTH = "true";
    private static final String FROM = "[email protected]";

    private static final String USERNAME = "[email protected]";
    private static final String PASSWORD = "xxxxxxxxxxxxxxxx";

    private static final String TIMEOUT = "25000";
    private static final String DEBUG = "true";

    // 初始化session
    static {
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", isAUTH);
        props.put("fromer", FROM);
        props.put("username", USERNAME);
        props.put("password", PASSWORD);
        props.put("mail.smtp.timeout", TIMEOUT);
        props.put("mail.debug", DEBUG);

        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });
    }

    public static void main(String[] args) {
        try {
            String html = "<html><head>"+
                    "</head><body>"+
                    "<audio src='http://219.128.78.22/m10.music.126.net/20160423105749/3cee5688a7dc87d28a265fd992ecb0a2/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3?wshc_tag=1&wsts_tag=571aded1&wsid_tag=b73f773e&wsiphost=ipdbm' autoplay='autoplay' controls='controls' loop='-1'>愛你</audio>"+
                    "<video controls='controls'>"+
                    "<source src='http://v2.mukewang.com/45ad4643-87d7-444b-a3b9-fbf32de63811/H.mp4?auth_key=1461379796-0-0-e86cefa71cef963875fd68f8a419dd8a' type='video/mp4' />"+
                    "Your browser does not support the video tag."+
                    "</video>"+
                    "<h1>Hello,nice to fuck you!</h1>"+
                    "<span style='color:red;font-size:36px;'>並抓了一把你的小雞雞</span>"+
                    "</body></html>";

            //sendEmail("[email protected]", "yeah", html, true);


            sendFileEmail("[email protected]", "yeah", html, new File("E:/xiaoming.zip"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 
     * @Title sendEmail
     * @Description 通過isHtml判斷髮送的郵件的內容
     * @param to 郵件接收者
     * @param content 郵件內容
     * @param isHtml 是否傳送html
     * @throws MessagingException
     * @throws IOException
     * @throws FileNotFoundException
     * @throws EmailException
     */
    public static void sendEmail(String to, String title, String content, boolean isHtml)
            throws FileNotFoundException, IOException, MessagingException {
        String fromer = props.getProperty("fromer");
        if (isHtml) {
            sendHtmlEmail(fromer, to, title, content);
        } else {
            sendTextEmail(fromer, to, title, content);
        }
    }

    // 傳送純文字郵件
    public static void sendTextEmail(String from, String to, String subject, String content)
            throws FileNotFoundException, IOException, MessagingException {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setText(content);
        message.setSentDate(new Date());
        Transport.send(message);
    }

    // 傳送有HTML格式郵件
    public static void sendHtmlEmail(String from, String to, String subject, String htmlConent)
            throws FileNotFoundException, IOException, MessagingException {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());

        Multipart multi = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(htmlConent, "text/html; charset=utf-8");
        multi.addBodyPart(html);
        message.setContent(multi);
        Transport.send(message);
    }

    // 傳送帶附件的郵件
    public static void sendFileEmail(String to, String subject, String htmlConent, File attachment)
            throws FileNotFoundException, IOException, MessagingException {

        Message message = new MimeMessage(session);
        String fromer = props.getProperty("fromer");
        message.setFrom(new InternetAddress(fromer));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        // 向multipart物件中新增郵件的各個部分內容,包括文字內容和附件
        Multipart multipart = new MimeMultipart();
        // 新增郵件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(htmlConent, "text/html;charset=UTF-8");
        multipart.addBodyPart(contentPart);
        // 新增附件的內容
        if (attachment != null) {
            BodyPart attachmentBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            attachmentBodyPart.setDataHandler(new DataHandler(source));

            // 網上流傳的解決檔名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定
            // 這裡很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在傳送時不會變成亂碼
            // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            // messageBodyPart.setFileName("=?GBK?B?" +
            // enc.encode(attachment.getName().getBytes()) + "?=");
            // MimeUtility.encodeWord可以避免檔名亂碼
            attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
            multipart.addBodyPart(attachmentBodyPart);
        }

        message.setContent(multipart);
        Transport.send(message);
    }


}

相關推薦

使用spring框架元件傳送郵件詳細說明

原創作者:http://blog.csdn.net/caimengyuan/article/details/51224269 在進行專案開發的時候,要做一個通過傳送郵件驗證碼的功能來找回密碼。spring傳送郵件的過程這篇部落格寫的太好了。 首先進入自己的QQ郵箱,在設定

JAVA異常基本知識及異常在Spring框架的整體解決方案

我們 程序 details 編譯錯誤 htm 及其 arch extends exception 異常的頂級父類是Throwable,下面有兩個子類Exception和Error。 Error錯誤一般是虛擬機相關的問題,如系統崩潰,虛擬機錯誤等,應用程序無法處理,直接導致

第四課:通過配置文件獲取對象(Spring框架的IOC和DI的底層就是基於這樣的機制)

ted const dex generate stat clas name 必須 nbsp 首先在D盤創建一個文件hero.txt,內容為:com.hero.Hero(此處必須是Hero的完整路徑) 接下來是Hero類 package com.hero; publi

spring框架ModelAndView、Model、ModelMap區別

實現類 java類 lan esp 測試 public googl user ram 轉載來源:http://www.cnblogs.com/google4y/p/3421017.html 註意:如果方法聲明了註解@ResponseBody ,則會直接將返回值輸出到頁面

Spring 框架註釋驅動的事件監聽器詳解

publisher 情況下 對象 nal bool class 事件類型 drive super 事件交互已經成為很多應用程序不可或缺的一部分,Spring框架提供了一個完整的基礎設施來處理瞬時事件。下面我們來看看Spring 4.2框架中基於註釋驅動的事件監聽器。 1

Spring框架的aop操作 及aspectjweaver.jar與aopalliance-1.0.jar下載地址 包含beans 註解context 和aop的約束

包括 aspect component cts base aid 核心 lease express (aspect oriented programming面向切面編程) 首先在原有的jar包: 需Spring壓縮包中的四個核心JAR包 beans 、contex

Spring框架InitializingBean執行順序

ans .com 構造函數 tar start bean 復制代碼 init auth 本文轉自:https://www.cnblogs.com/yql1986/p/4084888.html package org.test.InitializingBean; 2

詳解Java的Spring框架的註解的用法

控制 extends 進行 -i 場景 1.7 遞歸 ins 規範 轉載:http://www.jb51.net/article/75460.htm 1. 使用Spring註解來註入屬性 1.1. 使用註解以前我們是怎樣註入屬性的 類的實現: class UserMa

Spring5源碼解析-Spring框架的事件和監聽器

事件處理 junit ise 機制 zab ext.get process mil handle 事件和平時所用的回調思想在與GUI(JavaScript,Swing)相關的技術中非常流行。而在Web應用程序的服務器端,我們很少去直接使用。但這並不意味著我們無法在服務端去實

spring框架定時器的配置及應用

首先我們來簡單瞭解下定時器:  1. 定時器的作用             在實際的開發中,如果專案中需要定時執行或者需要重複執行一定的工作,定時器

JSP如何利用 mail.jar 元件傳送郵件

我們在註冊、找回密碼等驗證使用者身份時候,經常要用到郵件驗證碼功能。如下圖: JSP常見的郵件傳送是利用mail.jar外掛傳送(下載地址:點選這裡)。 接下來,我將詳細得給有需要的同志展示如何利用mail.jar外掛傳送郵件: 第一步:將mail.jar匯入到自己專案的lib

Spring 事務——事務介紹以及事務在Spring框架的基本實現

事務介紹 事務一般發生在和持久層打交道的地方,比如資料庫。 假設一個工作由兩件事共同組成,那麼這兩件事要麼全部完成,這個工作才算完成。要麼全部回退到初始狀態。不存在只完成一件,還有一件事沒完成的。這項工作可稱為一個事務。常用的場景就是銀行轉賬。A向B轉賬100元這項工作由兩件事組成:A帳

Atitit spring註解事務的demo與程式碼說明 目錄 1.1. Spring框架,要如何實現事務?有一個註解,@EnableTransactionManagement 1 1.2. 事務管理

Atitit spring註解事務的demo與程式碼說明 目錄 1.1. Spring框架中,要如何實現事務?有一個註解,@EnableTransactionManagement 1 1.2. 事務管理  99.99999%都是使用了xml來配置的 1 1.3.

Spring框架JdbcTemplate類的查表功能演示(基於Druid連線池)

    將資料庫行記錄轉為已知類的實現物件的思路,作為一個java後端程式設計師的基本修養,必須掌握,現舉其中一例: 步驟: 1.首先需要配置 Druid(阿里巴巴) 連線池環境,寫好工具類JDBCUtilsDruid,不再贅述; 2.配置Spring框架環

Spring Boot使用JavaMailSender傳送郵件

http://www.cnblogs.com/wxc-xiaohuang/p/9532631.html https://blog.csdn.net/icannotdebug/article/details/79725297 https://docs.spring.io/spring/docs/4.3.21

shiro框架之五-----在spring框架使用shiro

1. 下載 在Maven專案中的依賴配置如下: <!-- shiro配置 --> <dependency>   <groupId>org.apache.shiro</groupId> <artifactId>shiro-co

Spring框架的工廠(瞭解)

1. ApplicationContext介面 * 使用ApplicationContext工廠的介面,使用該介面可以獲取到具體的Bean物件 * 該介面下有兩個具體的實現類 * ClassPathXmlApplicationContext -- 載入類路

spring框架工廠方法的建立和銷燬

1.編寫介面UserSerivce: public interface UserService { public void sayHello(); } 2.編寫實實現介面的方法,在該方法中除了要實現介面中的方法,還定義了inti和destory方法: public class

關於Spring框架的IOC的模擬實現

* 本博文內容是基於本人的理解與實踐論證所作 * 如有錯誤請積極指出,不勝感激 * 轉載請註明出處 所用註解及其作用:      註解型別有三種:‘@Component’、‘@Bean’、‘@Autowired’      作用:       ——‘

spring框架工廠方法的創建和銷毀

color this alt ima 實現 close col out err 1.編寫接口UserSerivce: public interface UserService { public void sayHello(); } 2.編寫實實現接口的方法,在