1. 程式人生 > >Java 收取 和 傳送 郵件+SSL

Java 收取 和 傳送 郵件+SSL

 

這裡使用 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.");
 }
}

現在傳送郵件時會發生異常資訊,如下:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:419)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:342)
Caused by: javax.mail.MessagingException: Exception reading response;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260)
    ... 4 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1611)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
    ... 8 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:285)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:191)
    at sun.security.validator.Validator.validate(Validator.java:218)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
    ... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:280)
    ... 26 more

原因是需要儲存安裝證書

Q: When connecting to my mail server over SSL I get an exception like "unable to find valid certification path to requested target".
A: Your server is probably using a test certificate or self-signed certificate instead of a certificate signed by a commercial Certificate Authority. You'll need to install the server's certificate into your trust store. The InstallCert program will help.

使用DOS命令進入InstallCert.java 存放目錄
執行 javac InstallCert.java 將InstallCert.java 編譯成 .class檔案

在執行 java InstallCert smtp.xyz.com:465【其中xyz是要使用的mail,例如:smtp.126.com】【465是埠號】

得到jssecacerts檔案後複製到jdk1.6.0_14\jre\lib\security目錄 

然後再發送郵件就OK了

程式碼都是測試過的,執行沒問題。

InstallCert.java資源已經上傳到CSDN上,需要的可以去資源頁下載。

參考: