Send email using Java program

Source: Internet
Author: User

at present, many large websites forget login password common form is to use the mailbox to retrieve the password recently done projects also have this need to summarize now so that later to see the package used  Mailapi.jar smtp.jar These two jar files  Encapsulates the entity that sent the message package Com.tes;import Java.util.date;import Java.util.properties;import javax.mail.authenticator;import Javax.mail.message;import Javax.mail.multipart;import Javax.mail.passwordauthentication;import javax.mail.Session ; import Javax.mail.transport;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 javen * @Email [Email protected]*/ Public classMail {String to="";//RecipientString from="";//SenderString host ="";//SMTP HostString username ="";//User nameString Password ="";//PasswordString subject ="";//Message SubjectString content ="";//message body     PublicMail () {} PublicMail (string to, string from, string host, string username, string password, string subject, string content) {         This. to =to ;  This. from= from;  This. Host =host;  This. Username =username;  This. Password =password;  This. Subject =subject;  This. Content =content; }    /** * Convert the theme to Chinese * * @param strText * @return*/     Publicstring Transferchinese (String strText) {Try{StrText= Mimeutility.encodetext (NewString (Strtext.getbytes (),"GB2312"),"GB2312","B"); } Catch(Exception e) {e.printstacktrace (); }        returnStrText; }    /** * Send mail * * @return Successful return True, Failure returns false*/     PublicBoolean sendMail () {//Construct mail SessionProperties props =system.getproperties (); Props.put ("Mail.smtp.host", host); Props.put ("Mail.smtp.auth","true"); Session Session=session.getdefaultinstance (Props,NewAuthenticator () { Publicpasswordauthentication getpasswordauthentication () {return Newpasswordauthentication (username, password);        }                }); Try {            //constructs a mimemessage and sets a basic value to create a Message objectMimeMessage msg =NewMimeMessage (session); //Set Message contentMsg.setfrom (NewInternetAddress ( from)); System. out. println ( from); //map e-mail addresses to Internet addressesInternetaddress[] Address = {Newinternetaddress (To)}; /** * setrecipient (message.recipienttype type, address * address), used to set the recipient of the message. <br> * There are two parameters, the first parameter is the receiver type, the second parameter is the receiver. <br> * Recipient type can be message.recipienttype. To,message *. Recipienttype.cc and Message.recipienttype.bcc,to represent the primary recipient, CC represents CC *, and BCC indicates a secret CC.             The receiver, like the sender, typically uses internetaddress objects. */msg.setrecipients (Message.RecipientType.TO, address); //set the title of a messageSubject =Transferchinese (subject);            Msg.setsubject (subject); //Construction MultipartMultipart MP =NewMimemultipart (); //add body to multipartMimeBodyPart mbpcontent =NewMimeBodyPart (); //Set message content (plain text format)//Mbpcontent.settext (content); //Set the message content (HTML format)Mbpcontent.setcontent (Content,"Text/html;charset=utf-8"); //Add to MimeMessage (multipart representative body)Mp.addbodypart (mbpcontent); //add MimeMessage to multipartMsg.setcontent (MP); //sets the time the message is sent. Msg.setsentdate (NewDate ()); //Send mailtransport.send (msg); } Catch(Exception e) {e.printstacktrace (); return false; }        return true; }     PublicString Getto () {returnto ; }     Public voidSetto (String to) { This. to =to ; }     PublicString Getfrom () {return  from; }     Public voidSetfrom (String from) {         This. from= from; }     PublicString gethost () {returnhost; }     Public voidSethost (String host) { This. Host =host; }     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }     PublicString Getsubject () {returnsubject; }     Public voidSetsubject (String subject) { This. Subject =subject; }     PublicString getcontent () {returncontent; }     Public voidsetcontent (String content) { This. Content =content; }}
Test send a message to your own mailbox package com.tes;/** * @author javen * @Email [Email protected] **/ Public classTest { Public Static voidMain (string[] args) {Mail mail=NewMail (); Mail.setto ("[email protected]"); Mail.setfrom ("[email protected]");//your e-mailMail.sethost ("smtp.163.com");//smtp.qq.comMail.setusername ("XXX");//UserMail.setpassword ("xxxx");//PasswordMail.setsubject ("[Test] Retrieve your account password"); Mail.setcontent ("Test Outgoing Mail"); if(Mail.sendmail ()) {System. out. println ("sent successfully"); } }}
Reprinted from: http://www.cnblogs.com/zyw-205520/p/3738258.html

Send email using Java program

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.