java mail 筆記

來源:互聯網
上載者:User

在網上找到例子,這是原文連結:http://www.cnblogs.com/liyazhou/archive/2010/08/20/1804927.html。

但是測試的時候總是報錯,上網找了很多文章,終於找到解決方案(可惜,我還是不懂原理)。

現在把代碼貼上這裡,做個記錄,也方便各位遇到這個問題可以參考。

另外,除了要載入java mail的jar包,還需要一個叫jaf的東東。

還有,有網友分享了java mail的研究心得,值得參考:http://www.cnblogs.com/qianru/archive/2010/10.html。

1、發送郵件


MailSenderInfo

import java.util.Properties;public class MailSenderInfo {// 發送郵件的伺服器的IP和連接埠private String mailServerHost;private String mailServerPort = "587";// 郵件寄件者的地址private String fromAddress;// 郵件接收者的地址private String toAddress;// 登陸郵件發送伺服器的使用者名稱和密碼private String userName;private String password;// 是否需要身分識別驗證private boolean validate = true;// 郵件主題private String subject;// 郵件的常值內容private String content;// 郵件附件的檔案名稱private String[] attachFileNames;/** * 獲得郵件會話屬性 */public Properties getProperties() {Properties p = new Properties();p.put("mail.smtp.host", this.mailServerHost);p.put("mail.smtp.port", this.mailServerPort);p.put("mail.smtp.auth", "true");return p;}public String getMailServerHost() {return mailServerHost;}public void setMailServerHost(String mailServerHost) {this.mailServerHost = mailServerHost;}public String getMailServerPort() {return mailServerPort;}public void setMailServerPort(String mailServerPort) {this.mailServerPort = mailServerPort;}public boolean isValidate() {return validate;}public void setValidate(boolean validate) {this.validate = validate;}public String[] getAttachFileNames() {return attachFileNames;}public void setAttachFileNames(String[] fileNames) {this.attachFileNames = fileNames;}public String getFromAddress() {return fromAddress;}public void setFromAddress(String fromAddress) {this.fromAddress = fromAddress;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getToAddress() {return toAddress;}public void setToAddress(String toAddress) {this.toAddress = toAddress;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getContent() {return content;}public void setContent(String textContent) {this.content = textContent;}}

MyAuth

import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;public class MyAuth extends Authenticator{//一定要繼承AuthenticatorString userName = null;String password = null;public MyAuth() {}public MyAuth(String username, String password) {this.userName = username;this.password = password;}protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(userName, password);}}

SimpleMailSender

import java.util.Date;   import java.util.Properties;  import javax.mail.Address;   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 SimpleMailSender {/**    * 以文字格式設定發送郵件    * @param mailInfo 待發送的郵件的資訊    */       public boolean sendTextMail(MailSenderInfo mailInfo) {         // 判斷是否需要身份認證         MyAuth auth = null;         Properties pro = mailInfo.getProperties();        if (mailInfo.isValidate()) {         // 如果需要身份認證,則建立一個密碼驗證器           auth = new MyAuth(mailInfo.getUserName(), mailInfo.getPassword());         }        // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session         Session sendMailSession = Session.getDefaultInstance(pro,auth);         try {         // 根據session建立一個郵件訊息         Message mailMessage = new MimeMessage(sendMailSession);         // 建立郵件寄件者地址         Address from = new InternetAddress(mailInfo.getFromAddress());         // 設定郵件訊息的寄件者         mailMessage.setFrom(from);         // 建立郵件的接收者地址,並設定到郵件訊息中         Address to = new InternetAddress(mailInfo.getToAddress());         mailMessage.setRecipient(Message.RecipientType.TO,to);         // 設定郵件訊息的主題         mailMessage.setSubject(mailInfo.getSubject());         // 設定郵件訊息發送的時間         mailMessage.setSentDate(new Date());         // 設定郵件訊息的主要內容         String mailContent = mailInfo.getContent();         mailMessage.setText(mailContent);         // 發送郵件         Transport.send(mailMessage);        return true;         } catch (MessagingException ex) {             ex.printStackTrace();         }         return false;       }             /**        * 以HTML格式發送郵件        * @param mailInfo 待發送的郵件資訊        */       public boolean sendHtmlMail(MailSenderInfo mailInfo){         // 判斷是否需要身份認證         MyAuth authenticator = null;        Properties pro = mailInfo.getProperties();        //如果需要身份認證,則建立一個密碼驗證器          if (mailInfo.isValidate()) {           authenticator = new MyAuth(mailInfo.getUserName(), mailInfo.getPassword());        }         // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session         Session sendMailSession = Session.getDefaultInstance(pro,authenticator);         try {         // 根據session建立一個郵件訊息         Message mailMessage = new MimeMessage(sendMailSession);         // 建立郵件寄件者地址         Address from = new InternetAddress(mailInfo.getFromAddress());         // 設定郵件訊息的寄件者         mailMessage.setFrom(from);         // 建立郵件的接收者地址,並設定到郵件訊息中         Address to = new InternetAddress(mailInfo.getToAddress());         // Message.RecipientType.TO屬性工作表示接收者的類型為TO         mailMessage.setRecipient(Message.RecipientType.TO,to);         // 設定郵件訊息的主題         mailMessage.setSubject(mailInfo.getSubject());         // 設定郵件訊息發送的時間         mailMessage.setSentDate(new Date());         // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象         Multipart mainPart = new MimeMultipart();         // 建立一個包含HTML內容的MimeBodyPart         BodyPart html = new MimeBodyPart();         // 設定HTML內容         html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");         mainPart.addBodyPart(html);         // 將MiniMultipart對象設定為郵件內容         mailMessage.setContent(mainPart);         // 發送郵件         Transport.send(mailMessage);         return true;         } catch (MessagingException ex) {             ex.printStackTrace();         }         return false;       }   }

MailTest

public class MailTest {public static void main(String[] args) {MailSenderInfo mailInfo = new MailSenderInfo();mailInfo.setMailServerHost("smtp.qq.com");mailInfo.setMailServerPort("25");//普通為“25”,SSL則是“465”或“587”,可以在郵箱設定裡獲得參考mailInfo.setUserName("xxx@qq.com");mailInfo.setPassword("xxx");//使用者名稱和密碼,實際上是登入郵箱mailInfo.setFromAddress("xxx@qq.com");//寄件者,就是上面的登入名稱mailInfo.setToAddress("yyy@163.com");//收件者mailInfo.setSubject("我的工作郵件測試");//標題mailInfo.setContent("hello,\n\t這個是測試,希望一切正常。");//內容// 這個類主要來發送郵件SimpleMailSender sms = new SimpleMailSender();sms.sendTextMail(mailInfo);// 發送文體格式//sms.sendHtmlMail(mailInfo);// 發送html格式}}

2、

3、

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.