Spring Boot整合郵件發送

概述html

  Spring Boot下面整合了郵件服務器,使用Spring Boot可以輕鬆實現郵件發送;整理下最近使用Spring Boot發送郵件和注意事項;java

Maven包依賴android

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Spring Boot的配置web

spring.mail.host=smtp.servie.com
spring.mail.username=用戶名  //發送方的郵箱
spring.mail.password=密碼  //對於qq郵箱而言 密碼指的就是發送方的受權碼
spring.mail.port=465

spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
#是否用啓用加密傳送的協議驗證項
#注意:在spring.mail.password處的值是須要在郵箱設置裏面生成的受權碼,這個不是真實的密碼。

Spring 代碼實現spring

package com.dbgo.webservicedemo.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component("emailtool")
public class EmailTool {
    @Autowired
    private JavaMailSender javaMailSender;


    public void sendSimpleMail(){
        MimeMessage message = null;
        try {
            message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("jiajinhao@dbgo.cn");
            helper.setTo("653484166@qq.com");
            helper.setSubject("標題:發送Html內容");

            StringBuffer sb = new StringBuffer();
            sb.append("<h1>大標題-h1</h1>")
                    .append("<p style='color:#F00'>紅色字</p>")
                    .append("<p style='text-align:right'>右對齊</p>");
            helper.setText(sb.toString(), true);
            FileSystemResource fileSystemResource=new FileSystemResource(new File("D:\76678.pdf"))
            helper.addAttachment("電子發票",fileSystemResource);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

非Spring Boot下發送電子郵件:服務器

Maven包依賴session

<dependencies>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.2</version>
        </dependency>
  </dependencies>

DEMO1代碼事例app

package com.justin.framework.core.utils.email;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
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.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 使用SMTP協議發送電子郵件
 */
public class sendEmailCode {


    // 郵件發送協議
    private final static String PROTOCOL = "smtp";

    // SMTP郵件服務器
    private final static String HOST = "mail.tdb.com";

    // SMTP郵件服務器默認端口
    private final static String PORT = "25";

    // 是否要求身份認證
    private final static String IS_AUTH = "true";

    // 是否啓用調試模式(啓用調試模式可打印客戶端與服務器交互過程時一問一答的響應消息)
    private final static String IS_ENABLED_DEBUG_MOD = "true";

    // 發件人
    private static String from = "tdbjrcrm@tdb.com";

    // 收件人
    private static String to = "db_yangruirui@tdbcwgs.com";

    private static String senduserName="tdbjrcrm@tdb.com";
    private static String senduserPwd="New*2016";

    // 初始化鏈接郵件服務器的會話信息
    private static Properties props = null;

    static {
        props = new Properties();
        props.setProperty("mail.enable", "true");
        props.setProperty("mail.transport.protocol", PROTOCOL);
        props.setProperty("mail.smtp.host", HOST);
        props.setProperty("mail.smtp.port", PORT);
        props.setProperty("mail.smtp.auth", IS_AUTH);//視狀況而定
        props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD);
    }


    /**
     * 發送簡單的文本郵件
     */
    public static boolean sendTextEmail(String to,int code) throws Exception {
        try {
            // 建立Session實例對象
            Session session1 = Session.getDefaultInstance(props);

            // 建立MimeMessage實例對象
            MimeMessage message = new MimeMessage(session1);
            // 設置發件人
            message.setFrom(new InternetAddress(from));
            // 設置郵件主題
            message.setSubject("內燃機註冊驗證碼");
            // 設置收件人
            message.setRecipient(RecipientType.TO, new InternetAddress(to));
            // 設置發送時間
            message.setSentDate(new Date());
            // 設置純文本內容爲郵件正文
            message.setText("您的驗證碼是:"+code+"!驗證碼有效期是10分鐘,過時後請從新獲取!"
                    + "中國內燃機學會");
            // 保存並生成最終的郵件內容
            message.saveChanges();

            // 得到Transport實例對象
            Transport transport = session1.getTransport();
            // 打開鏈接
            transport.connect("meijiajiang2016", "");
            // 將message對象傳遞給transport對象,將郵件發送出去
            transport.sendMessage(message, message.getAllRecipients());
            // 關閉鏈接
            transport.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        sendHtmlEmail("db_yangruirui@tdbcwgs.com", 88888);
    }

    /**
     * 發送簡單的html郵件
     */
    public static boolean sendHtmlEmail(String to,int code) throws Exception {
        // 建立Session實例對象
        Session session1 = Session.getInstance(props, new MyAuthenticator());

        // 建立MimeMessage實例對象
        MimeMessage message = new MimeMessage(session1);
        // 設置郵件主題
        message.setSubject("內燃機註冊");
        // 設置發送人
        message.setFrom(new InternetAddress(from));
        // 設置發送時間
        message.setSentDate(new Date());
        // 設置收件人
        message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
        // 設置html內容爲郵件正文,指定MIME類型爲text/html類型,並指定字符編碼爲gbk
        message.setContent("<div style='width: 600px;margin: 0 auto'><h3 style='color:#003E64; text-align:center; '>內燃機註冊驗證碼</h3><p style=''>尊敬的用戶您好:</p><p style='text-indent: 2em'>您在註冊內燃機帳號,這次的驗證碼是:"+code+",有效期10分鐘!若是過時請從新獲取。</p><p style='text-align: right; color:#003E64; font-size: 20px;'>中國內燃機學會</p></div>","text/html;charset=utf-8");

        //設置自定義發件人暱稱
        String nick="";
        try {
            nick=javax.mail.internet.MimeUtility.encodeText("中國內燃機學會");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        message.setFrom(new InternetAddress(nick+" <"+from+">"));
        // 保存並生成最終的郵件內容
        message.saveChanges();

        // 發送郵件
        try {
            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 發送帶內嵌圖片的HTML郵件
     */
    public static void sendHtmlWithInnerImageEmail() throws MessagingException {
        // 建立Session實例對象
        Session session = Session.getDefaultInstance(props, new MyAuthenticator());

        // 建立郵件內容
        MimeMessage message = new MimeMessage(session);
        // 郵件主題,並指定編碼格式
        message.setSubject("帶內嵌圖片的HTML郵件", "utf-8");
        // 發件人
        message.setFrom(new InternetAddress(from));
        // 收件人
        message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
        // 抄送
        message.setRecipient(RecipientType.CC, new InternetAddress("java_test@sohu.com"));
        // 密送 (不會在郵件收件人名單中顯示出來)
        message.setRecipient(RecipientType.BCC, new InternetAddress("417067629@qq.com"));
        // 發送時間
        message.setSentDate(new Date());

        // 建立一個MIME子類型爲「related」的MimeMultipart對象
        MimeMultipart mp = new MimeMultipart("related");
        // 建立一個表示正文的MimeBodyPart對象,並將它加入到前面建立的MimeMultipart對象中
        MimeBodyPart htmlPart = new MimeBodyPart();
        mp.addBodyPart(htmlPart);
        // 建立一個表示圖片資源的MimeBodyPart對象,將將它加入到前面建立的MimeMultipart對象中
        MimeBodyPart imagePart = new MimeBodyPart();
        mp.addBodyPart(imagePart);

        // 將MimeMultipart對象設置爲整個郵件的內容
        message.setContent(mp);

        // 設置內嵌圖片郵件體
        DataSource ds = new FileDataSource(new File("resource/firefoxlogo.png"));
        DataHandler dh = new DataHandler(ds);
        imagePart.setDataHandler(dh);
        imagePart.setContentID("firefoxlogo.png");  // 設置內容編號,用於其它郵件體引用

        // 建立一個MIME子類型爲"alternative"的MimeMultipart對象,並做爲前面建立的htmlPart對象的郵件內容
        MimeMultipart htmlMultipart = new MimeMultipart("alternative");
        // 建立一個表示html正文的MimeBodyPart對象
        MimeBodyPart htmlBodypart = new MimeBodyPart();
        // 其中cid=androidlogo.gif是引用郵件內部的圖片,即imagePart.setContentID("androidlogo.gif");方法所保存的圖片
        htmlBodypart.setContent("<span style='color:red;'>這是帶內嵌圖片的HTML郵件哦!!!<img src=\"cid:firefoxlogo.png\" /></span>","text/html;charset=utf-8");
        htmlMultipart.addBodyPart(htmlBodypart);
        htmlPart.setContent(htmlMultipart);

        // 保存並生成最終的郵件內容
        message.saveChanges();

        // 發送郵件
        Transport.send(message);
    }

    /**
     * 發送帶內嵌圖片、附件、多收件人(顯示郵箱姓名)、郵件優先級、閱讀回執的完整的HTML郵件
     */
    public static void sendMultipleEmail() throws Exception {
        String charset = "utf-8";   // 指定中文編碼格式
        // 建立Session實例對象
        Session session = Session.getInstance(props,new MyAuthenticator());

        // 建立MimeMessage實例對象
        MimeMessage message = new MimeMessage(session);
        // 設置主題
        message.setSubject("使用JavaMail發送混合組合類型的郵件測試");
        // 設置發送人
        message.setFrom(new InternetAddress(from,"新浪測試郵箱",charset));
        // 設置收件人
        message.setRecipients(RecipientType.TO,
                new Address[] {
                        // 參數1:郵箱地址,參數2:姓名(在客戶端收件只顯示姓名,而不顯示郵件地址),參數3:姓名中文字符串編碼
                        new InternetAddress("java_test@sohu.com", "張三_sohu", charset),
                        new InternetAddress("xyang0917@163.com", "李四_163", charset),
                }
        );
        // 設置抄送
        message.setRecipient(RecipientType.CC, new InternetAddress("xyang0917@gmail.com","王五_gmail",charset));
        // 設置密送
        message.setRecipient(RecipientType.BCC, new InternetAddress("xyang0917@qq.com", "趙六_QQ", charset));
        // 設置發送時間
        message.setSentDate(new Date());
        // 設置回覆人(收件人回覆此郵件時,默認收件人)
        message.setReplyTo(InternetAddress.parse("\"" + MimeUtility.encodeText("田七") + "\" <417067629@qq.com>"));
        // 設置優先級(1:緊急   3:普通    5:低)
        message.setHeader("X-Priority", "1");
        // 要求閱讀回執(收件人閱讀郵件時會提示回覆發件人,代表郵件已收到,並已閱讀)
        message.setHeader("Disposition-Notification-To", from);

        // 建立一個MIME子類型爲"mixed"的MimeMultipart對象,表示這是一封混合組合類型的郵件
        MimeMultipart mailContent = new MimeMultipart("mixed");
        message.setContent(mailContent);

        // 附件
        MimeBodyPart attach1 = new MimeBodyPart();
        MimeBodyPart attach2 = new MimeBodyPart();
        // 內容
        MimeBodyPart mailBody = new MimeBodyPart();

        // 將附件和內容添加到郵件當中
        mailContent.addBodyPart(attach1);
        mailContent.addBodyPart(attach2);
        mailContent.addBodyPart(mailBody);

        // 附件1(利用jaf框架讀取數據源生成郵件體)
        DataSource ds1 = new FileDataSource("resource/Earth.bmp");
        DataHandler dh1 = new DataHandler(ds1);
        attach1.setFileName(MimeUtility.encodeText("Earth.bmp"));
        attach1.setDataHandler(dh1);

        // 附件2
        DataSource ds2 = new FileDataSource("resource/如何學好C語言.txt");
        DataHandler dh2 = new DataHandler(ds2);
        attach2.setDataHandler(dh2);
        attach2.setFileName(MimeUtility.encodeText("如何學好C語言.txt"));

        // 郵件正文(內嵌圖片+html文本)
        MimeMultipart body = new MimeMultipart("related");  //郵件正文也是一個組合體,須要指明組合關係
        mailBody.setContent(body);

        // 郵件正文由html和圖片構成
        MimeBodyPart imgPart = new MimeBodyPart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        body.addBodyPart(imgPart);
        body.addBodyPart(htmlPart);

        // 正文圖片
        DataSource ds3 = new FileDataSource("resource/firefoxlogo.png");
        DataHandler dh3 = new DataHandler(ds3);
        imgPart.setDataHandler(dh3);
        imgPart.setContentID("firefoxlogo.png");

        // html郵件內容
        MimeMultipart htmlMultipart = new MimeMultipart("alternative");
        htmlPart.setContent(htmlMultipart);
        MimeBodyPart htmlContent = new MimeBodyPart();
        htmlContent.setContent(
                "<span style='color:red'>這是我本身用java mail發送的郵件哦!" +
                        "<img src='cid:firefoxlogo.png' /></span>"
                , "text/html;charset=gbk");
        htmlMultipart.addBodyPart(htmlContent);

        // 保存郵件內容修改
        message.saveChanges();

        /*File eml = buildEmlFile(message);
        sendMailForEml(eml);*/

        // 發送郵件
        Transport.send(message);
    }

    /**
     * 將郵件內容生成eml文件
     * @param message 郵件內容
     */
    public static File buildEmlFile(Message message) throws MessagingException, FileNotFoundException, IOException {
        File file = new File("c:\\" + MimeUtility.decodeText(message.getSubject())+".eml");
        message.writeTo(new FileOutputStream(file));
        return file;
    }

    /**
     * 發送本地已經生成好的email文件
     */
    public static void sendMailForEml(File eml) throws Exception {
        // 得到郵件會話
        Session session = Session.getInstance(props,new MyAuthenticator());
        // 得到郵件內容,即發生前生成的eml文件
        InputStream is = new FileInputStream(eml);
        MimeMessage message = new MimeMessage(session,is);
        //發送郵件
        Transport.send(message);
    }

    /**
     * 向郵件服務器提交認證信息
     */
    static class MyAuthenticator extends Authenticator {

        private String username = "";

        private String password = "";

        public MyAuthenticator() {
            super();
            this.password=senduserPwd;
            this.username=senduserName;
        }

        public MyAuthenticator(String username, String password) {
            super();
            this.username = username;
            this.password = password;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(username, password);
        }
    }
}

DEMO2代碼事例:框架

package com.justin.framework.core.utils.email;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class MailManagerUtils { //發送郵件 public static boolean sendMail(Email email) { String subject = email.getSubject(); String content = email.getContent(); String[] recievers = email.getRecievers(); String[] copyto = email.getCopyto(); String attbody = email.getAttbody(); String[] attbodys = email.getAttbodys(); if(recievers == null || recievers.length <=0) { return false; } try { Properties props =new Properties(); props.setProperty("mail.enable", "true"); props.setProperty("mail.protocal", "smtp"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.user", "tdbjrcrm@tdb.com"); props.setProperty("mail.pass", "New***"); props.setProperty("mail.smtp.host","mail.tdb.com"); props.setProperty("mail.smtp.from","tdbjrcrm@tdb.com"); props.setProperty("mail.smtp.fromname","tdbVC"); // 建立一個程序與郵件服務器的通訊 Session mailConnection = Session.getInstance(props, null); Message msg = new MimeMessage(mailConnection); // 設置發送人和接受人 Address sender = new InternetAddress(props.getProperty("mail.smtp.from")); // 多個接收人 msg.setFrom(sender); Set<InternetAddress> toUserSet = new HashSet<InternetAddress>(); // 郵箱有效性較驗 for (int i = 0; i < recievers.length; i++) { if (recievers[i].trim().matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)+$")) { toUserSet.add(new InternetAddress(recievers[i].trim())); } } msg.setRecipients(Message.RecipientType.TO, toUserSet.toArray(new InternetAddress[0])); // 設置抄送 if (copyto != null) { Set<InternetAddress> copyToUserSet = new HashSet<InternetAddress>(); // 郵箱有效性較驗 for (int i = 0; i < copyto.length; i++) { if (copyto[i].trim().matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)+$")) { copyToUserSet.add(new InternetAddress(copyto[i].trim())); } } // msg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto)); msg.setRecipients(Message.RecipientType.CC, copyToUserSet.toArray(new InternetAddress[0])); } // 設置郵件主題 msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B")); // 中文亂碼問題 // 設置郵件內容 BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=UTF-8"); // 中文 Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); /********************** 發送附件 ************************/ if (attbody != null) { String[] filePath = attbody.split(";"); for (String filepath : filePath) { //設置信件的附件(用本地機上的文件做爲附件) BodyPart mdp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filepath); DataHandler dh = new DataHandler(fds); mdp.setFileName(MimeUtility.encodeText(fds.getName())); mdp.setDataHandler(dh); multipart.addBodyPart(mdp); } //把mtp做爲消息對象的內容 msg.setContent(multipart); }; if (attbodys != null) { for (String filepath : attbodys) { //設置信件的附件(用本地機上的文件做爲附件) BodyPart mdp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filepath); DataHandler dh = new DataHandler(fds); mdp.setFileName(MimeUtility.encodeText(fds.getName())); mdp.setDataHandler(dh); multipart.addBodyPart(mdp); } //把mtp做爲消息對象的內容 msg.setContent(multipart); } ; /********************** 發送附件結束 ************************/ // 先進行存儲郵件 msg.saveChanges(); System.out.println("正在發送郵件...."); Transport trans = mailConnection.getTransport(props.getProperty("mail.protocal")); // 郵件服務器名,用戶名,密碼 trans.connect(props.getProperty("mail.smtp.host"), props.getProperty("mail.user"), props.getProperty("mail.pass")); trans.sendMessage(msg, msg.getAllRecipients()); System.out.println("發送郵件成功!"); // 關閉通道 if (trans.isConnected()) { trans.close(); } return true; } catch (Exception e) { System.err.println("郵件發送失敗!" + e); return false; } finally { } } // 發信人,收信人,回執人郵件中有中文處理亂碼,res爲獲取的地址 // http默認的編碼方式爲ISO8859_1 // 對含有中文的發送地址,使用MimeUtility.decodeTex方法 // 對其餘則把地址從ISO8859_1編碼轉換成gbk編碼 public static String getChineseFrom(String res) { String from = res; try { if (from.startsWith("=?GB") || from.startsWith("=?gb") || from.startsWith("=?UTF")) { from = MimeUtility.decodeText(from); } else { from = new String(from.getBytes("ISO8859_1"), "GBK"); } } catch (Exception e) { e.printStackTrace(); } return from; } // 轉換爲GBK編碼 public static String toChinese(String strvalue) { try { if (strvalue == null) return null; else { strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK"); return strvalue; } } catch (Exception e) { return null; } }
public static void main(String[] args) { Email email=new Email(); email.setRecievers(new String[]{"db_yangruirui@tdbcwgs.com"}); email.setSubject("TEST測件"); email.setContent("TEST測試"); sendMail(email); } }
相關文章
相關標籤/搜索