Java-工具类之发送邮件
生活随笔
收集整理的這篇文章主要介紹了
Java-工具类之发送邮件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 步驟
- 實例
- 依賴包
- 不帶有附件的郵件
- 工具類一
- 工具類二
- 帶有附件的郵件
- 不帶有附件的郵件
步驟
使用properties創建一個Session對象
使用Session創建Message對象,然后設置郵件主題和正文,如果需要發送附件,就需要用到Multipart對象
使用Transport對象發送郵件
實例
代碼已托管到 https://github.com/yangshangwei/commonUtils
依賴包
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail --><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>${javax.mail.version}</version></dependency>不帶有附件的郵件
工具類一
package com.artisan.commonUtils.mail;import java.util.Properties;import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage;import com.sun.mail.util.MailSSLSocketFactory; /*** * @ClassName: SendEmailUtil* @Description: 發送郵件工具類* @author: Mr.Yang* @date: 2017年8月28日 下午4:50:35*/ public class SendEmailUtil {/*** * * @Title: sendEmail* * @Description: 發送郵件工具類方法* * @param sendEmail* 發件人地址* @param sendEmailPwd* 授權碼代替密碼(更安全) 授權碼的獲取:進入個人郵箱,點擊設置–>賬戶, SMTP服務選項 默認情況下這個選項是不開啟的。* 點擊開啟騰訊會進行身份驗證,身份驗證通過以后,會收到一個用于使用SMTP的16位口令,* 驗證身份的過程中把收到的口令保存下來,因為后面要使用SMTP功能必須要用到這個口令。* @param title* 郵件標題* @param content* 郵件內容* @param toEmilAddress* 收件人地址* @throws Exception* * @return: void*/public static void sendEmail(String sendEmail, String sendEmailPwd, String title, String content,String[] toEmilAddress) throws Exception {Properties props = new Properties();// 開啟debug調試,以便在控制臺查看props.setProperty("mail.debug", "true");// 設置郵件服務器主機名props.setProperty("mail.host", "smtp.qq.com");// 發送服務器需要身份驗證props.setProperty("mail.smtp.auth", "true");// 發送郵件協議名稱props.setProperty("mail.transport.protocol", "smtp");// 開啟SSL加密,否則會失敗MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);props.put("mail.smtp.ssl.enable", "true");props.put("mail.smtp.ssl.socketFactory", sf);Session session = Session.getInstance(props);Message msg = new MimeMessage(session);// 發送的郵箱地址msg.setFrom(new InternetAddress(sendEmail));// 設置標題msg.setSubject(title);// 設置內容msg.setContent(content, "text/html;charset=gbk;");Transport transport = session.getTransport();// 設置服務器以及賬號和密碼// 這里端口改成465transport.connect("smtp.qq.com", sendEmail, sendEmailPwd);// 發送到的郵箱地址transport.sendMessage(msg, getAddress(toEmilAddress));if(transport!=null){try {transport.close();} catch (MessagingException e) {e.printStackTrace();}}}/*** * @Title: getAddress* @Description: 遍歷收件人信息* @param emilAddress* @return* @throws Exception* @return: Address[]*/private static Address[] getAddress(String[] emilAddress) throws Exception {Address[] address = new Address[emilAddress.length];for (int i = 0; i < address.length; i++) {address[i] = new InternetAddress(emilAddress[i]);}return address;}/*** * * @Title: main* * @Description: 測試* * @param args* @throws Exception* * @return: void*/public static void main(String[] args) throws Exception {/*** * @param sendEmail 發件人地址* * @param sendEmailPwd* 授權碼代替密碼(更安全) * @param title* 郵件標題* @param content* 郵件內容* @param toEmilAddress* 收件人地址*/SendEmailUtil.sendEmail("xxxxx@qq.com", "xxxxxxx", "testEmail", "testcontent",new String[] { "xxxxx@gmail.com", "xxxx@qq.com" });} }/*** 在發郵件過程中有的人會發送不成功,出現如下錯誤: * javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure* * 這個是jdk導致的,jdk里面有一個jce的包,安全性機制導致的訪問https會報錯,官網上有替代的jar包,換掉就好了* * 對應包的下載地址:* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html* * 下載好后,直接替換掉本地JDK中的對應的兩的包就好了。* */測試結果:
工具類二
#smtp server mail.smtp.host=smtp.qq.com #Authentication mail.smtp.auth=true #--------------------------------------------------------------#Account of sender's mailbox mail.sender.username=xxxxxxx@qq.com #Authorization code of sender's mailbox mail.sender.password=xxxxxxx package com.artisan.commonUtils.mail;import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.Properties;import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility;import com.sun.mail.util.MailSSLSocketFactory; /*** * @ClassName: SendMailUtil2* @Description: 發送郵件工具類* @author: Mr.Yang* @date: 2017年8月28日 下午4:50:17*/ public class SendMailUtil2 {/*** Message對象將存儲我們實際發送的電子郵件信息,* Message對象被作為一個MimeMessage對象來創建并且需要知道應當選擇哪一個JavaMail session。*/private MimeMessage message;/*** Session類代表JavaMail中的一個郵件會話。* 每一個基于JavaMail的應用程序至少有一個Session(可以有任意多的Session)。* * JavaMail需要Properties來創建一個session對象。* 尋找"mail.smtp.host" 屬性值就是發送郵件的主機* 尋找"mail.smtp.auth" 身份驗證,目前免費郵件服務器都需要這一項*/private Session session;/**** 郵件是既可以被發送也可以被受到。JavaMail使用了兩個不同的類來完成這兩個功能:Transport 和 Store。 * Transport 是用來發送信息的,而Store用來收信。這里我們只需要用到Transport對象。*/private Transport transport;private String mailHost="";private String sender_username="";private String sender_password="";private Properties properties = new Properties();/** 初始化方法*/public SendMailUtil2(boolean debug) {InputStream in = SendMailUtil2.class.getResourceAsStream("SMTPMailServer.properties");try {properties.load(in);this.mailHost = properties.getProperty("mail.smtp.host");this.sender_username = properties.getProperty("mail.sender.username");this.sender_password = properties.getProperty("mail.sender.password");// 開啟SSL加密,否則會失敗MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);properties.put("mail.smtp.ssl.enable", "true");properties.put("mail.smtp.ssl.socketFactory", sf);} catch (IOException e) {e.printStackTrace();} catch (GeneralSecurityException e) {e.printStackTrace();}session = Session.getInstance(properties);session.setDebug(debug);//開啟后有調試信息message = new MimeMessage(session);}/*** 發送郵件* * @param subject* 郵件主題* @param sendHtml* 郵件內容* @param receiveUser* 收件人地址*/public void doSendHtmlEmail(String subject, String emailContent,String[] toEmailAddress) {try {// 發件人//InternetAddress from = new InternetAddress(sender_username);// 下面這個是設置發送人的Nick nameInternetAddress from = new InternetAddress(MimeUtility.encodeWord("小工匠")+" <"+sender_username+">");message.setFrom(from);// 郵件主題message.setSubject(subject);// 郵件內容,也可以使純文本"text/plain"message.setContent(emailContent, "text/html;charset=UTF-8");// 保存郵件message.saveChanges();transport = session.getTransport("smtp");// smtp驗證 用戶名和授權碼transport.connect(mailHost, sender_username, sender_password);// 發送transport.sendMessage(message, getAddress(toEmailAddress));System.out.println("send email successfully ");} catch (Exception e) {e.printStackTrace();}finally {if(transport!=null){try {transport.close();} catch (MessagingException e) {e.printStackTrace();}}}}/*** * @Title: getAddress* @Description: 遍歷收件人信息* @param emilAddress* @return* @throws Exception* @return: Address[]*/private static Address[] getAddress(String[] emilAddress) throws Exception {Address[] address = new Address[emilAddress.length];for (int i = 0; i < address.length; i++) {address[i] = new InternetAddress(emilAddress[i]);}return address;}public static void main(String[] args) {SendMailUtil2 se = new SendMailUtil2(true);// 開啟調試se.doSendHtmlEmail("1郵件主題", "郵件內容", new String[]{"xxxxx@gmail.com","xxxxxxxx@qq.com"});} }測試結果:
帶有附件的郵件
#smtp server mail.smtp.host=smtp.qq.com #Authentication mail.smtp.auth=true #--------------------------------------------------------------#Account of sender's mailbox mail.sender.username=xxxxxxx@qq.com #Authorization code of sender's mailbox mail.sender.password=xxxxxxx package com.artisan.commonUtils.mail;import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.Properties;import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.MessagingException; 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;import com.sun.mail.util.MailSSLSocketFactory;/*** * @ClassName: SendEmailWithAttachment* @Description: Email發送附件 [如果需要發送附件,就需要用到Multipart對象]* @author: Mr.Yang* @date: 2017年8月28日 下午4:49:35*/ public class SendEmailWithAttachment {private MimeMessage message;private Session session;private Transport transport;private String mailHost = "";private String sender_username = "";private String sender_password = "";private Properties properties = new Properties();/** 初始化方法*/public SendEmailWithAttachment(boolean debug) {InputStream in = SendEmailWithAttachment.class.getResourceAsStream("SMTPMailServer.properties");try {properties.load(in);this.mailHost = properties.getProperty("mail.smtp.host");this.sender_username = properties.getProperty("mail.sender.username");this.sender_password = properties.getProperty("mail.sender.password");// 開啟SSL加密,否則會失敗MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);properties.put("mail.smtp.ssl.enable", "true");properties.put("mail.smtp.ssl.socketFactory", sf);} catch (IOException e) {e.printStackTrace();} catch (GeneralSecurityException e) {e.printStackTrace();}session = Session.getInstance(properties);session.setDebug(debug);// 開啟后有調試信息message = new MimeMessage(session);}/*** 發送郵件* * @param subject* 郵件主題* @param sendHtml* 郵件內容* @param receiveUser* 收件人地址* @param attachment* 附件*/public void doSendHtmlEmail(String subject, String sendHtml, String[] receiveUsers, File attachment) {try {// 發件人InternetAddress from = new InternetAddress(sender_username);message.setFrom(from);// 郵件主題message.setSubject(subject);// 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件Multipart multipart = new MimeMultipart();// 添加郵件正文BodyPart contentPart = new MimeBodyPart();contentPart.setContent(sendHtml, "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);}// 將multipart對象放到message中message.setContent(multipart);// 保存郵件message.saveChanges();transport = session.getTransport("smtp");// smtp驗證transport.connect(mailHost, sender_username, sender_password);// 發送transport.sendMessage(message, getAddress(receiveUsers));System.out.println("send success!");} catch (Exception e) {e.printStackTrace();} finally {if (transport != null) {try {transport.close();} catch (MessagingException e) {e.printStackTrace();}}}}/*** @Title: getAddress* @Description: 遍歷收件人信息* @param emilAddress* @return* @throws Exception* @return: Address[]*/private static Address[] getAddress(String[] emilAddress) throws Exception {Address[] address = new Address[emilAddress.length];for (int i = 0; i < address.length; i++) {address[i] = new InternetAddress(emilAddress[i]);}return address;}public static void main(String[] args) {SendEmailWithAttachment se = new SendEmailWithAttachment(true);File attached = new File("D:\\workspace\\ws-java-base\\commonUtils\\pom.xml");se.doSendHtmlEmail("郵件主題帶有附件", "郵件內容", new String[]{"yswcomeon@gmail.com"}, attached);}}測試結果:
總結
以上是生活随笔為你收集整理的Java-工具类之发送邮件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring-AOP @AspectJ切
- 下一篇: Spring-AOP @AspectJ切