程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java應用JavaMail API發送和吸收郵件的代碼示例

Java應用JavaMail API發送和吸收郵件的代碼示例

編輯:關於JAVA

Java應用JavaMail API發送和吸收郵件的代碼示例。本站提示廣大學習愛好者:(Java應用JavaMail API發送和吸收郵件的代碼示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java應用JavaMail API發送和吸收郵件的代碼示例正文


應用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 = "[email protected]"; 
    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("[email protected]"));//發件人 
     
    Transport transport = session.getTransport(); 
    transport.connect("smtp.126.com", 25, sendUserName, sendPassword);//銜接發件人應用發件的辦事器 
    transport.sendMessage(message, new Address[]{new InternetAddress("[email protected]")});//接收郵件 
    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 = "[email protected]";// 發送郵件須要銜接的辦事器的用戶名 
 
  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("[email protected]")); 
    message.setSubject("Demo2JavaCode發送郵件測試,采取Authenticator");// 設置主題 
    message.setRecipients(Message.RecipientType.TO, InternetAddress 
        .parse("[email protected],[email protected]"));// 發送 
    message.setRecipients(Message.RecipientType.CC, InternetAddress 
        .parse("[email protected]"));// 抄送 
    message 
        .setContent( 
            "<span  mce_>假如您看到,證實測試勝利了!</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 = "[email protected]"; 
      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")+"/"<[email protected]>")); 
    msg.setSubject("這是我的第一份龐雜郵件");//設置郵件主題 
    msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(MimeUtility.encodeText("王翔攀")+"<[email protected]>,"+MimeUtility.encodeText("三毛")+"<[email protected]>")); 
 
    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", "http://mimg.126.net/logo/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 = "[email protected]";
    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("吸收終了!");
  }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved