您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關Spring Boot中怎么整合郵件發送,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
什么是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.com spring.mail.username=用戶名 //發送方的郵箱 spring.mail.password=密碼 //對于qq郵箱而言 密碼指的就是發送方的授權碼 spring.mail.properties.mail.smtp.auth=true spring.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("jiajinhao@dbgo.cn"); helper.setTo("653484166@qq.com"); helper.setSubject("標題:發送Html內容"); StringBuffer sb = new StringBuffer(); sb.append("<h2>大標題-h2</h2>") .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 = "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'><h4 style='color:#003E64; text-align:center; '>內燃機注冊驗證碼</h4><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 attach2 = new MimeBodyPart(); MimeBodyPart attach3 = new MimeBodyPart(); // 內容 MimeBodyPart mailBody = new MimeBodyPart(); // 將附件和內容添加到郵件當中 mailContent.addBodyPart(attach2); mailContent.addBodyPart(attach3); mailContent.addBodyPart(mailBody); // 附件1(利用jaf框架讀取數據源生成郵件體) DataSource ds1 = new FileDataSource("resource/Earth.bmp"); DataHandler dh2 = new DataHandler(ds1); attach2.setFileName(MimeUtility.encodeText("Earth.bmp")); attach2.setDataHandler(dh2); // 附件2 DataSource ds2 = new FileDataSource("resource/如何學好C語言.txt"); DataHandler dh3 = new DataHandler(ds2); attach3.setDataHandler(dh3); attach3.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 dh4 = new DataHandler(ds3); imgPart.setDataHandler(dh4); 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); } }
以上就是Spring Boot中怎么整合郵件發送,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。