Use javamail to receive/send Gmail mail (SSL)

Source: Internet
Author: User
Tags email account gmail mail

Gmail has enabled POP3 and SMTP services, please refer to the http://www.javayou.com/showlog.jspe? Log_id = 490

Unlike other mailboxes, POP3 and SMTP provided by Gmail use Secure Sockets Layer SSL, so regular javamail programs cannot send and receive emails, the following code uses javamail to collect and send emails to Gmail:

 

1. receive emails

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 receive Gmail emails
* @ 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 normal javamail operations
Session session = session. getdefaultinstance (props, null );

// Replace the red part with your email account and password.
Urlname urln = new urlname ("POP3", "pop.gmail.com", 995, null,
"[Email account]", "[email 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 ("Number of inbox Emails:" + messages. Length );
For (INT I = 0; I <messages. length; I ++ ){
// Email sender
String from = decodetext (messages [I]. getfrom () [0]. tostring ());
Internetaddress IA = new internetaddress (from );
System. Out. println ("from:" + ia. getpersonal () + '(' + ia. getaddress () + ')');
// Mail title
System. Out. println ("title:" + messages [I]. getsubject ());
// Mail size
System. Out. println ("Size:" + messages [I]. getsize ());
// Email sending time
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. send an email

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 emails
* @ 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 = "[email account]";
Final string Password = "[email 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.,
Internetaddress. parse ("[recipient address]", false ));
MSG. setsubject ("hello ");
MSG. settext ("how are you ");
MSG. setsentdate (new date ());
Transport. Send (MSG );

System. Out. println ("message sent .");
}
}

For the resolution of mail please see http://www.javayou.com/showlog.jspe? Log_id = 372
More articles about javamail http://www.javayou.com/main.jspe? Query = javamail

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.