Java collect and send mail +ssl__java

Source: Internet
Author: User
Tags email account gmail mail mail account

Use Gmail email to test here

1. Receive mail

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;  /** * used to collect gmail mail * @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");

  The following steps are the same as the general JavaMail operation session = Session.getdefaultinstance (props,null); Please replace the red part with your email account number and password urlname URLN = new URLName ("POP3", "pop.gmail.com", 995,null,

    "E-mail Account", "Mailbox Password");

  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 ("Mail Number of Inbox:" + messages.length); for (int i = 0; i < messages.length i++) {//Mail sender String from = Decodetext (Messages[i].getfrom () [0].tostrin

    g ());

    InternetAddress ia = new internetaddress (from);

    System.out.println ("From:" + ia.getpersonal () + ' (' +ia.getaddress () + ') ');

    Message title System.out.println ("title:" + Messages[i].getsubject ());

    Message size System.out.println ("size:" + messages[i].getsize ());

   Mail delivery time System.out.println ("DATE:" + messages[i].getsentdate ());

   Finally {try {Inbox.close (false);

    catch (Exception e) {} try {Store.close (); The catch (Exception e) {}}} protected static String Decodetext (String text) throws Unsupportedencodingexceptio

  n {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. Send mail

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; /** * Use Gmail to send mail * @author Winter Lau */public class Gmailsender {public static void main (string[] args) throw

  S 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 = "Mailbox Account";

  Final String password = "Mailbox Password"; Session session = Session.getdefaultinstance (props, New authenticator () {protected passwordauthentication Getpasswo

      Rdauthentication () {Return to 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 ("[Recipient address]", false));

  Msg.setsubject ("Hello");

  Msg.settext ("How to Are You");

  Msg.setsentdate (New Date ());

  Transport.send (msg);
 SYSTEM.OUT.PRINTLN ("message sent.");
 }
}

An exception message occurs when you send a message now, as follows:

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)
... 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)
... Num

The reason is that you need to save the installation certificate

The official QA Http://java.sun.com/products/javamail/FAQ.html#installcert

Q:when connecting to me mail server over SSL I get a exception like "Unable to find valid certification path to Requeste D target ".
A:your server is probably using a test certificate or self-signed certificate instead of a certificate signed by a Commer cial Certificate Authority. You'll need to install the server's certificate into your trust store. The Installcert program would help.

Use DOS command to enter Installcert.java storage directory
Run Javac Installcert.java to compile Installcert.java into a. class file

In running Java installcert smtp.xyz.com:465 "where XYZ is the mail to use, for example: smtp.126.com" "465 is the port number"

Copy to jdk1.6.0_14\jre\lib\security directory after jssecacerts file is obtained

And then you send the mail and it's OK.

The code has been tested, and running is no problem.

Installcert.java resources have been uploaded to the csdn and need to be downloaded from the resource page.

Download Address: http://download.csdn.net/detail/liguo9860/3684166

Reference:

http://fableking.iteye.com/blog/929726

http://a51480139.blog.163.com/blog/static/336814592008414294592/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.