Java使用JavaMail API發送和內送郵件的程式碼範例_java

來源:互聯網
上載者:User

使用Javamail發送郵件,必需的jar包(請下載javamail的源檔案,官方下載頁:http://www.oracle.com/technetwork/java/javamail/index-138643.html):
mailapi.jar。定義了收發郵件所使用到的介面API;
smtp.jar。包含了發送郵件使用到的類;
pop3.jar。包含了收郵件使用到的類;
我們通常發送郵件使用的協議是smtp協議,接受郵件使用的協議是pop3協議。或者,我們直接將mail.jar加入到工程,這個jar包裡邊包含了java收發郵件所有的介面和類。
 
常用的類:

  •      javax.mail.Session;                                                    -------->儲存串連伺服器所需要的資訊;
  •      javax.mail.Message;                                                  -------->郵件體,儲存郵件的內容;
  •      javax.mail.Transport;                                                 -------->發送郵件的載體
  •      javax.mail.internet.InternetAddress;                         -------->郵件的地址資訊

發送郵件

下邊,我先列出使用Java發送郵件的最簡單的一個小測試樣本:

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;  /**  *  * QQ(mail.qq.com):POP3伺服器(連接埠995)SMTP伺服器(連接埠465或587)。  *  */ public class Demo1 {    /**    * @param args    * @throws MessagingException    */   public static void main(String[] args) throws MessagingException {          String sendUserName = "wangxiangpan@126.com";     String sendPassword = "pwd";          Properties properties = new Properties();     properties.setProperty("mail.smtp.auth", "true");//伺服器需要認證     properties.setProperty("mail.transport.protocol", "smtp");//聲明發送郵件使用的連接埠          Session session = Session.getInstance(properties);     session.setDebug(true);//同意在當前線程的控制台列印與伺服器對話資訊          Message message = new MimeMessage(session);//構建發送的資訊     message.setText("你好,我是Champion.Wong!");//資訊內容     message.setFrom(new InternetAddress("wangxiangpan@126.com"));//寄件者          Transport transport = session.getTransport();     transport.connect("smtp.126.com", 25, sendUserName, sendPassword);//串連寄件者使用發件的伺服器     transport.sendMessage(message, new Address[]{new InternetAddress("492134880@qq.com")});//接受郵件     transport.close();   }  } 

一般的,我們使用Authenticator把使用者名稱和密碼封裝起來,不透明!所以:

import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage;  import junit.framework.TestCase;  /**  * javamail 發送郵件  * @author Champion Wong  * Message.addRecipient(Message.Recipient recipient, Address address); 發郵件的時候指定收件者和收件者的角色  * Message.RecipientType.TO 收件者  * Message.RecipientType.CC 抄送,即發郵件的時候順便給另一個人抄一份,不用回複!但是,上邊的收件者可以看到你都抄送給了誰  * Message.RecipientType.BCC 暗送,也是發郵件的時候順便給另一個人暗發一份,但是,不同於上邊的是,收件者不能看到你都暗送給了誰  *  */ public class Demo2 extends TestCase {    private static final String sendUserName = "wangxiangpan@126.com";// 發送郵件需要已連線的服務器的使用者名稱    private static final String sendPassword = "pwd";// 發送郵件需要已連線的服務器的密碼    private static final String sendProtocol = "smtp";// 發送郵件使用的連接埠    private static final String sendHostAddress = "smtp.126.com";// 發送郵件使用的伺服器的地址    public void test() throws AddressException, MessagingException {      Properties properties = new Properties();     properties.setProperty("mail.smtp.auth", "true");// 伺服器需要認證     properties.setProperty("mail.transport.protocol", sendProtocol);// 聲明發送郵件使用的連接埠     properties.setProperty("mail.host", sendHostAddress);// 發送郵件的伺服器位址      Session session = Session.getInstance(properties, new Authenticator() {       protected PasswordAuthentication getPasswordAuthentication() {         return new PasswordAuthentication(sendUserName, sendPassword);       }     });     session.setDebug(true);//在後台列印發送郵件的即時資訊      Message message = new MimeMessage(session);     message.setFrom(new InternetAddress("wangxiangpan@126.com"));     message.setSubject("Demo2JavaCode發送郵件測試,採用Authenticator");// 設定主題     message.setRecipients(Message.RecipientType.TO, InternetAddress         .parse("492134880@qq.com,wangxiangpan@126.com"));// 發送     message.setRecipients(Message.RecipientType.CC, InternetAddress         .parse("msn_wangxiangpan@hotmail.com"));// 抄送     message         .setContent(             "<span style="font-size:20px; color:#FFCCFF" mce_style="font-size:20px; color:#FFCCFF">如果您看到,證明測試成功了!</span>",             "text/html;charset=gbk");      Transport.send(message);//發送郵件   } } 

我們發送一個比較複雜的郵件,包括附件,圖文:

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties;  import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; 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;  /**  *  * @author Administrator Mr XP.Wang  * MimeMultipart 一般電子郵件的容器是Multipart,定義了增加及刪除電子郵件各部分內容的方法,  *        但是其是抽象類別,需要其子類MimeMultipart來時用MimeMessage對象  * MimeBodyPart 是BodyPart具體用於mimeMessage的一個子類,MimeBodyPart對象代表一個  *       mimeMultipart對象的每一個部分  * MimeUtility.encodeText(String cn)用於解決郵件中的頭部資訊中中文的亂碼問題  *  */ public class Demo3_test {    public static void main(String[] args) throws Exception {          Properties properties = new Properties();     properties.setProperty("mail.smtp.auth", "true");// 伺服器需要認證     properties.setProperty("mail.transport.protocol", "smtp");// 聲明發送郵件使用的連接埠     properties.setProperty("mail.host", "smtp.126.com");// 發送郵件的伺服器位址          Session session = Session.getInstance(properties, new Authenticator() {       String sendUserName = "wangxiangpan@126.com";       String sendPassword = "pwd";       protected PasswordAuthentication getPasswordAuthentication() {         return new PasswordAuthentication(sendUserName,             sendPassword);       }     });     session.setDebug(true);          MimeMessage msg = new MimeMessage(session);// 聲明一個郵件體     msg.setFrom(new InternetAddress("/""+MimeUtility.encodeText("Mr XP.Wang")+"/"<wangxiangpan@126.com>"));     msg.setSubject("這是我的第一份複雜郵件");//設定郵件主題     msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(MimeUtility.encodeText("王翔攀")+"<wangxiangpan@126.com>,"+MimeUtility.encodeText("三毛")+"<492134880@qq.com>"));      MimeMultipart msgMultipart = new MimeMultipart("mixed");// 標明郵件的組合關係,混合的關係     msg.setContent(msgMultipart);// 設定郵件體           MimeBodyPart attch1 = new MimeBodyPart();// 附件1     MimeBodyPart attch2 = new MimeBodyPart();// 附件2     MimeBodyPart content = new MimeBodyPart();// 郵件的本文,混合體(圖片+文字)      // 將附件和本文設定到這個郵件體中     msgMultipart.addBodyPart(attch1);     msgMultipart.addBodyPart(attch2);     msgMultipart.addBodyPart(content);           // 設定第一個附件     DataSource ds1 = new FileDataSource("F:/ACCP5.0/檔案/ssh配置.txt");// 指定附件的資料來源     DataHandler dh1 = new DataHandler(ds1);// 附件的資訊     attch1.setDataHandler(dh1);// 指定附件     attch1.setFileName("ssh.txt");      // 設定第二個附件     DataSource ds2 = new FileDataSource("resource/48.jpg");// 指定附件的資料來源     DataHandler dh2 = new DataHandler(ds2);// 附件的資訊     attch2.setDataHandler(dh2);// 指定附件     attch2.setFileName("48.jpg");      //設定郵件的本文     MimeMultipart bodyMultipart = new MimeMultipart("related");//依賴關係     content.setContent(bodyMultipart);//指定本文     MimeBodyPart htmlPart = new MimeBodyPart();     MimeBodyPart gifPart = new MimeBodyPart();     bodyMultipart.addBodyPart(htmlPart);     bodyMultipart.addBodyPart(gifPart);               DataSource gifds = new FileDataSource("resource/48.jpg");//本文的圖片     DataHandler gifdh = new DataHandler(gifds);     gifPart.setHeader("Content-Location", "yun_qi_img/126logo.gif");     gifPart.setDataHandler(gifdh);//設定本文的圖片          htmlPart.setContent("我只是來打醬油的,這是我的形象照!<img src="/" mce_src="/""http://mimg.126.net/logo/126logo.gif/">", "text/html;charset=gbk");//設定本文文字          msg.saveChanges();//儲存郵件          //將郵件儲存成檔案     OutputStream ops = new FileOutputStream("C:/Users/Administrator/Desktop/test.eml");     msg.writeTo(ops);     ops.close();          Transport.send(msg);              }  } 

收取郵件
樣本:Rose 收取最近一封郵件。

import java.util.Date;import java.util.Properties;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.NoSuchProviderException;import javax.mail.Session;import javax.mail.Store;public class FetchMail {  public static void main(String[] args) {    String protocol = "pop3";    boolean isSSL = true;    String host = "pop.163.com";    int port = 995;    String username = "rose@163.com";    String password = "rose";    Properties props = new Properties();    props.put("mail.pop3.ssl.enable", isSSL);    props.put("mail.pop3.host", host);    props.put("mail.pop3.port", port);    Session session = Session.getDefaultInstance(props);    Store store = null;    Folder folder = null;    try {      store = session.getStore(protocol);      store.connect(username, password);      folder = store.getFolder("INBOX");      folder.open(Folder.READ_ONLY);      int size = folder.getMessageCount();      Message message = folder.getMessage(size);      String from = message.getFrom()[0].toString();      String subject = message.getSubject();      Date date = message.getSentDate();      System.out.println("From: " + from);      System.out.println("Subject: " + subject);      System.out.println("Date: " + date);    } catch (NoSuchProviderException e) {      e.printStackTrace();    } catch (MessagingException e) {      e.printStackTrace();    } finally {      try {        if (folder != null) {          folder.close(false);        }        if (store != null) {          store.close();        }      } catch (MessagingException e) {        e.printStackTrace();      }    }    System.out.println("接收完畢!");  }}

聯繫我們

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