1. 程式人生 > >利用JavaMail傳送郵件:smtp.163.com

利用JavaMail傳送郵件:smtp.163.com

一、利用JavaMail傳送郵件案例:

1、maven專案結構:

2、先在pom.xml裡邊加入Javamail依賴,系統會根據座標自動下載mail包(前提是配置好了maven):

3、配置email.properties屬性檔案,主要是為了不更改程式碼的前提下,該改變傳送郵件的一些基本資訊:

4、實現傳送郵件的主體類SendMailUtils,程式碼下:

package top.hzelin.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.BodyPart; import javax.mail.Message; 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; public class SendMailUtils { private static String from = ""; private static String user = ""; private static String password = ""; /* * 讀取屬性檔案的內容,併為上面上個屬性賦初始值 */ static { Properties prop = new Properties(); InputStream is
= SendMailUtils.class.getClassLoader().getResourceAsStream("email.properties"); try { prop.load(is); from = prop.getProperty("from"); user=prop.getProperty("username"); password=prop.getProperty("password"); } catch (IOException e) { e.printStackTrace(); } } public static void sendMail(String to,String text,String title) { Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.163.com");//設定郵件伺服器主機名 props.put("mail.smtp.host", "smtp.163.com"); props.put("mail.smtp.auth", "true");//傳送伺服器需要身份驗證 Session session = Session.getDefaultInstance(props);//設定環境資訊 session.setDebug(true); MimeMessage message = new MimeMessage(session); Multipart multipart = null; BodyPart contentPart = null; Transport transport = null; try { message.setFrom(from);//設定發件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(title); multipart = new MimeMultipart();//設定附件 contentPart = new MimeBodyPart(); contentPart.setContent(text, "text/html;charset=utf-8"); multipart.addBodyPart(contentPart); message.setContent(multipart); message.saveChanges(); transport = session.getTransport("smtp"); transport.connect("smtp.163.com", user, password); transport.sendMessage(message, message.getAllRecipients()); } catch (MessagingException e) { e.printStackTrace(); }finally { try { transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } } }

5、測試傳送郵件功能是否可用SendEmailTest:

注意:email.properties配置檔案中的密碼應該是客戶端授權碼,不是登入密碼,設定位置如下: