什麼是Spring Boot
Spring Boot是一個框架,其設計目的是簡化Spring應用的初始搭建配置以及開發過程。該框架使用了特定的配置方式,從而使開發人員不在需要定義樣板化的配置。
Spring Boot的好處
1、配置簡單;
2、編碼簡單;
3、部署簡單;
4、監控簡單;
概述
Spring Boot下面整合了郵件服務器,使用Spring Boot能夠輕鬆實現郵件發送;整理下最近使用Spring Boot發送郵件和注意事項;
Maven包依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId></dependency>
Spring Boot的配置
spring.mail.host=smtp.servie.comspring.mail.username=用戶名//發送方的郵箱spring.mail.password=密碼//對於qq郵箱而言密碼指的就是發送方的授權碼spring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=false #是否用啟用加密傳送的協議驗證項spring.mail.properties.mail.smtp.starttls.required=fasle #是否用啟用加密傳送的協議驗證項#注意:在spring.mail.password處的值是需要在郵箱設置裡面生成的授權碼,這個不是真實的密碼。
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("[email protected]"); helper.setTo("[email protected]"); 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包依賴
<dependencies> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency> </dependencies>
DEMO1代碼事例
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 = "[email protected]"; // 收件人private static String to = "[email protected]"; private static String senduserName="[email protected]"; 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("[email protected]", 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("[email protected]")); // 密送(不會在郵件收件人名單中顯示出來) message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]")); // 發送時間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("[email protected]", "張三_sohu", charset), new InternetAddress("[email protected]", "李四_163", charset), } ); // 設置抄送message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]","王五_gmail",charset)); // 設置密送message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]", "趙六_QQ", charset)); // 設置發送時間message.setSentDate(new Date()); // 設置回复人(收件人回复此郵件時,默認收件人) message.setReplyTo(InternetAddress.parse("/"" + MimeUtility.encodeText("田七") + "/" <[email protected]>")); // 設置優先級(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", "[email protected]"); props.setProperty("mail.pass", "New***"); props.setProperty("mail.smtp.host","mail.tdb.com"); props.setProperty("mail.smtp.from","[email protected]"); 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[]{"[email protected]"}); email.setSubject("TEST測件"); email.setContent("TEST測試"); sendMail(email); }}總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。