Java發送Email

來源:互聯網
上載者:User

標籤:

 

  使用Java應用程式發送E-mail十分簡單,下面主要示範,發送普通的Email;發送HTML類型的Email;發送帶附件的Email。


一、    首先配置需要的jar包

  我們需要將mail.jar和activation.jar 兩個jar包添加到我們的CLASSPATH中,你可以在JavaMail API和JAF(JavaActivation Framework)下載最新的版本。如:


  


二、    發送普通的Email

  首先我們簡單封裝一個發送郵件的工具類。此外,我們打算採用的qq的郵件伺服器來發郵件,這就需要對寄件者進行身分識別驗證,急需要驗證寄件者的使用者名稱、密碼,所以我們定義了一個身分識別驗證的類。然後再寫一個測試類別即可測試。範例程式碼如下:

  2.1  發送郵件的工具類
public class SendEasyEmailToManyPeople {public static void SendEmail(String[] toAddress, String fromAddress, String hostAddress, String subject, String messageText) throws Exception {// 收件者電子郵箱【可以有多個收件者】InternetAddress[] sendTo = new InternetAddress[toAddress.length];for (int i = 0; i < toAddress.length; i++) {System.out.println("發送到:" + toAddress[i]);sendTo[i] = new InternetAddress(toAddress[i]);}// 寄件者電子郵箱String from = fromAddress;// 指定發送郵件的主機String host = hostAddress;// 擷取系統屬性Properties properties = System.getProperties();// 設定郵件伺服器properties.setProperty("mail.smtp.host", host);properties.put("mail.smtp.auth", "true"); // 這樣才能通過驗證MyAuthenticator myauth = new MyAuthenticator("你的郵箱地址", "你的郵箱密碼");// 擷取預設session對象Session session = Session.getDefaultInstance(properties, myauth);try {// 建立預設的 MimeMessage 對象MimeMessage message = new MimeMessage(session);// Set From: 頭部頭欄位message.setFrom(new InternetAddress(from));// Set To: 頭部頭欄位(type:要被設定為TO, CC 或者BCC. 這裡CC 代表抄送、BCC 代表秘密抄送y.// 舉例:Message.RecipientType.TO)message.addRecipients(Message.RecipientType.TO, sendTo);// Set Subject: 頭部頭欄位message.setSubject(subject);// 設定訊息體message.setText(messageText);// 發送訊息Transport.send(message);System.out.println("Sent message successfully....");} catch (MessagingException mex) {mex.printStackTrace();}}}

  2.2  身分識別驗證類
/** * 發信人許可權校正類 *  * @author wangzhipeng *  */public class MyAuthenticator extends javax.mail.Authenticator {private String strUser;private String strPwd;public MyAuthenticator(String user, String password) {this.strUser = user;this.strPwd = password;}protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(strUser, strPwd);}}

  2.3  測試類別
/** * 發送普通郵件的測試類別 *  * @author wangzhipeng *  */public class TestSendEmailToManyPeople {public static void main(String[] args) throws Exception {// 收件者郵箱【多個收件者】String[] toAddress = new String[] { "[email protected]", "[email protected]", "[email protected]" };// 寄件者郵箱String fromAddress = "你的郵箱地址";// 郵件伺服器類型(這裡為qq,如果要用163則為“smtp.163.com”)String hostAddress = "smtp.qq.com";// 郵件的主題String subject = "測試郵件——JAVA";// 郵件的本文String messageText = "Hello World阿斯蒂芬";// 發送郵件SendEasyEmailToManyPeople.SendEmail(toAddress, fromAddress, hostAddress, subject, messageText);}}

  2.4  測試結果

  三個人同時受到郵件,如:

  

  內容如下:

  


三、    發送HTML類型Email

  和上一個例子幾乎一樣,我們只需要在上面的【發送郵件的工具類】中使用setContent()方法來通過第二個參數為"text/html",來設定內容來指定要發送HTML內容即可,如:

  


  測試結果  


四、    發送帶附件的Email

  如,我們將我們項目根目錄下的一個file.txt檔案作為郵件的附件進行發送:

  

  需要在【發送普通的Email】的基礎上更改我們的【工具類】與【測試類別】,身分識別驗證類不變,範例程式碼如下:

  4.1  工具類
public class SendFileEmail {public static void SendEmail(String toAddress, String fromAddress, String hostAddress, String subject, String messageText, String fileRealPath) {// 收件者電子郵箱String to = toAddress;// 寄件者電子郵箱String from = fromAddress;// 指定發送郵件的主機String host = hostAddress;// 擷取系統屬性Properties properties = System.getProperties();// 設定郵件伺服器properties.setProperty("mail.smtp.host", host);properties.put("mail.smtp.auth", "true"); // 這樣才能通過驗證MyAuthenticator myauth = new MyAuthenticator("你的郵箱地址", "你的郵箱密碼");// 擷取預設session對象Session session = Session.getDefaultInstance(properties, myauth);try {// 建立預設的 MimeMessage 對象MimeMessage message = new MimeMessage(session);// Set From: 頭部頭欄位message.setFrom(new InternetAddress(from));// Set To: 頭部頭欄位message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// Set Subject: 頭部頭欄位message.setSubject(subject);// ------------------------------------------------------------------------------------------// 建立訊息部分BodyPart messageBodyPart = new MimeBodyPart();// 訊息messageBodyPart.setText(messageText);// 建立多重訊息Multipart multipart = new MimeMultipart();// 設定簡訊部分multipart.addBodyPart(messageBodyPart);// 附件部分messageBodyPart = new MimeBodyPart();String filename = fileRealPath;// 擷取附件實體路徑DataSource source = new FileDataSource(filename);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(filename);multipart.addBodyPart(messageBodyPart);// 發送完整訊息message.setContent(multipart);// ------------------------------------------------------------------------------------------// 發送訊息Transport.send(message);System.out.println("Sent message successfully....");} catch (MessagingException mex) {mex.printStackTrace();}}}

  4.2  測試類別
public class TestSendFileEmail {public static void main(String[] args) {// 收件者郵箱String toAddress = "[email protected]";// 寄件者郵箱String fromAddress = "你的郵箱地址";// 郵件伺服器類型(這裡為qq,如果要用163則為“smtp.163.com”)String hostAddress = "smtp.qq.com";// 郵件的主題String subject = "測試郵件——JAVA";// 郵件的本文String messageText = "Hello World!!!";// 擷取檔案絕對路徑String projectPath = System.getProperty("user.dir");String fileRealPath = projectPath.replace("\\", "/") + "/file.txt";// 發送郵件SendFileEmail.SendEmail(toAddress, fromAddress, hostAddress, subject, messageText, fileRealPath);}}

  4.3  測試結果  

五、    小結

       使用像qq、163、sohu、yahoo等郵件伺服器時,我們必須要先經過相應郵件伺服器的身分識別驗證才能發送郵件,以防止他人任意亂髮郵件。

  當然有些郵件服務系統是不需要驗證寄件者的授權的,所以可以在企事業單位的內部電子信箱系統很簡單的使用,例如,我們更改發郵件工具類中執行個體化Session過程,如下:

  

  這樣就可以省略下面的代碼(和身分識別驗證類):

  

 

Java發送Email

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.