利用JavaMail收/發Gmail郵件SSL

來源:互聯網
上載者:User
利用JavaMail收/發Gmail郵件SSL與其他郵箱不同的是Gmail提供的POP3和SMTP是使用安全通訊端層SSL的,因此常規的JavaMail程式是無法收發郵件的,下面是使用JavaMail如何收取Gmail郵件以及發送郵件的代碼:

1. 郵件收取

package lius.javamail.ssl;

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;

/**
 * 用於收取Gmail郵件
 * @author Winter Lau
 */
public class GmailFetch {
 
 public static void main(String argv[]) throws Exception {

  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

  // Get a Properties object
  Properties props = System.getProperties();
  props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
  props.setProperty("mail.pop3.socketFactory.fallback", "false");
  props.setProperty("mail.pop3.port", "995");
  props.setProperty("mail.pop3.socketFactory.port", "995");

  //以下步驟跟一般的JavaMail操作相同
  Session session = Session.getDefaultInstance(props,null);

  //請將紅色部分對應替換成你的郵箱帳號和密碼
  URLName urln = new URLName("pop3","pop.gmail.com",995,null,
    "[郵箱帳號]", "[郵箱密碼]");
  Store store = session.getStore(urln);
  Folder inbox = null;
  try {
   store.connect();
   inbox = store.getFolder("INBOX");
   inbox.open(Folder.READ_ONLY);
   FetchProfile profile = new FetchProfile();
   profile.add(FetchProfile.Item.ENVELOPE);
   Message[] messages = inbox.getMessages();
   inbox.fetch(messages, profile);
   System.out.println("收件匣的郵件數:" + messages.length);
   for (int i = 0; i < messages.length; i++) {
    //郵件寄件者
    String from = decodeText(messages[i].getFrom()[0].toString());
    InternetAddress ia = new InternetAddress(from);
    System.out.println("FROM:" + ia.getPersonal()+'('+ia.getAddress()+')');
    //郵件標題
    System.out.println("TITLE:" + messages[i].getSubject());
    //郵件大小
    System.out.println("SIZE:" + messages[i].getSize());
    //郵件發送時間
    System.out.println("DATE:" + messages[i].getSentDate());
   }
  } finally {
   try {
    inbox.close(false);
   } catch (Exception e) {}
   try {
    store.close();
   } catch (Exception e) {}
  }
 }
 
 protected static String decodeText(String text)
   throws UnsupportedEncodingException {
  if (text == null)
   return null;
  if (text.startsWith("=?GB") || text.startsWith("=?gb"))
   text = MimeUtility.decodeText(text);
  else
   text = new String(text.getBytes("ISO8859_1"));
  return text;
 }

}

2. 發送郵件

package lius.javamail.ssl;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

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;

/**
 * 使用Gmail發送郵件
 * @author Winter Lau
 */
public class GmailSender {

 public static void main(String[] args) throws AddressException, MessagingException {
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  // Get a Properties object
  Properties props = System.getProperties();
  props.setProperty("mail.smtp.host", "smtp.gmail.com");
  props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
  props.setProperty("mail.smtp.socketFactory.fallback", "false");
  props.setProperty("mail.smtp.port", "465");
  props.setProperty("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.auth", "true");
  final String username = "[郵箱帳號]";
  final String password = "[郵箱密碼]";
  Session session = Session.getDefaultInstance(props, new Authenticator(){
      protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(username, password);
      }});

       // -- Create a new message --
  Message msg = new MimeMessage(session);

  // -- Set the FROM and TO fields --
  msg.setFrom(new InternetAddress(username + "@mo168.com"));
  msg.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse("[收件者地址]",false));
  msg.setSubject("Hello");
  msg.setText("How are you");
  msg.setSentDate(new Date());
  Transport.send(msg);
  
  System.out.println("Message sent.");
 }
}

聯繫我們

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