Javamail Study Notes (3). Use SMTP protocol to send emails (all)

Source: Internet
Author: User
Package Org. yangxin. study. JM; import Java. io. file; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. util. date; import Java. util. properties; import javax. activation. datahandler; import javax. activation. datasource; import javax. activation. filedatasource; import javax. mail. address; import javax. Mail. authenticator; import javax. mail. message; import javax. mail. message. recipienttype; import javax. mail. messagingexception; 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. I Nternet. mimeutility;/*** use SMTP protocol to send emails */public class sendmailtest {// mail sending protocol private final static string protocol = "SMTP "; // SMTP Mail Server private final static string host = "smtp.sina.com"; // SMTP Mail Server default port private final static string port = "25 "; // whether authentication is required private final static string is_auth = "true"; // whether to enable debug mode (enable debug mode to print the response message that is answered when the client interacts with the server) private Final Static string is_enabled_debug_mod = "true"; // Sender Private Static string from = "xyang0917@sina.com"; // recipient Private Static string to = "xyang0917@163.com "; // initialize the session information Private Static Properties props = NULL; static {props = new properties (); props. setproperty ("mail. transport. protocol ", Protocol); props. setproperty ("mail. SMTP. host ", host); props. setproperty ("mail. SMTP. port ", Port); props. setproperty ("mail. SMTP. auth ", is_auth); props. setpropert Y ("mail. debug ", is_enabled_debug_mod);} public static void main (string [] ARGs) throws exception {// send text mail sendtextemail (); // send simple HTML mail sendhtmlemail (); // send the HTML email sendhtmlwithinnerimageemail () with embedded images; // send the combined message sendmultipleemail (); // send the generated EML email // sendmailforeml ();} /*** send a simple text email */public static void sendtextemail () throws exception {// create a session instance object session = session. getdefaultinstance (props ); // Create the mimemessage Instance Object mimemessage message = new mimemessage (session); // set the sender message. setfrom (New internetaddress (from); // sets the mail subject message. setsubject ("use javamail to send a simple text email"); // set the recipient message. setrecipient (recipienttype. to, new internetaddress (to); // sets the sending time message. setsentdate (new date (); // set the plain text content to the mail body message. settext ("use POP3 protocol to send text mail test !!! "); // Save and generate the final message. savechanges (); // obtain the transport Instance Object transport Transport = session. gettransport (); // open the connection transport. connect ("xyang0917", "123456abc"); // pass the message object to the transport object and send the email to transport. sendmessage (message, message. getallrecipients (); // close the connection to transport. close ();}/*** send simple HTML mail */public static void sendhtmlemail () throws exception {// create session instance object session = session. getinstance (Props, new myauthenticator (); // create the mimemessage Instance Object mimemessage message = new mimemessage (session); // set the message of the mail subject. setsubject ("HTML mail subject"); // sets the sender message. setfrom (New internetaddress (from); // sets the sending time message. setsentdate (new date (); // sets the recipient message. setrecipients (recipienttype. to, internetaddress. parse (to); // set the HTML content to the mail body, specify the MIME type to the text/html type, and specify the character encoding to gbkmessage. setcontent ("<span style = 'color: red; '> HT ML mail test... </span> "," text/html; charset = GBK "); // save and generate the final message. savechanges (); // send the transport email. send (Message);}/*** send an HTML email with embedded images */public static void sendhtmlwithinnerimageemail () throws messagingexception {// create a session instance object session = session. getdefaultinstance (props, new myauthenticator (); // create the mail content mimemessage message = new mimemessage (session); // The mail subject, and specify the message encoding format. setsubject ("h with Embedded Image TML mail "," UTF-8 "); // The sender message. setfrom (New internetaddress (from); // recipient message. setrecipients (recipienttype. to, internetaddress. parse (to); // CC message. setrecipient (recipienttype. CC, new internetaddress ("java_test@sohu.com"); // bcc (not displayed in the recipient list) message. setrecipient (recipienttype. BCC, new internetaddress ("417067629@qq.com"); // send time message. setsentdate (new date (); // create a mimemu with the mime subtype "related" Ltipart object mimemultipart MP = new mimemultipart ("related"); // create a mimebodypart object that represents the body, and add it to the previously created mimemultipart object mimebodypart htmlpart = new mimebodypart (); MP. addbodypart (htmlpart); // create a mimebodypart object that represents image resources and add it to the mimemultipart object created earlier. mimebodypart imagepart = new mimebodypart (); MP. addbodypart (imagepart); // sets the mimemultipart object to the message of the entire email. setcontent (MP); // set the embedded image email body datasource DS = new filedatasou RCE (new file ("resource/firefoxlogo.png"); datahandler DH = new datahandler (DS); imagepart. setdatahandler (DH); imagepart. setcontentid ("firefoxlogo.png"); // you can specify the content ID to reference other email bodies. // create a mimemultipart object with the mime subtype "alternative, mimemultipart htmlmultipart = new mimemultipart ("alternative"); // create a mimebodypart object mimebodypart htmlbodypart = new mimebodypart () that represents the html body (); // cid = androidlogo. gi F refers to the image inside the email, that is, imagepart. setcontentid ("androidlogo.gif"); htmlbodypart of the image saved by the method. setcontent ("<span style = 'color: red; '> This is an HTML email with embedded images !!!  </span> "," text/html; charset = UTF-8 "); htmlmultipart. addbodypart (htmlbodypart); htmlpart. setcontent (htmlmultipart); // save and generate the final message. savechanges (); // send the transport email. send (Message);}/*** send with embedded images, attachments, and multiple recipients (display email name), mail priority, read receipt complete HTML mail */public static void sendmultipleemail () throws exception {string charset = "UTF-8 "; // specify the Chinese encoding format // create a session instance object session = sessio N. getinstance (props, new myauthenticator (); // creates the mimemessage Instance Object mimemessage message = new mimemessage (session); // sets the topic message. setsubject ("use javamail to send a mail test of the hybrid combination type"); // set the sender message. setfrom (New internetaddress (from, "Sina test mailbox", charset); // set the recipient message. setrecipients (recipienttype. to, new address [] {// parameter 1: email address, parameter 2: Name (only the name is displayed on the client, not the email address), parameter 3: name Chinese character string encoding new internetaddress ("java_test@sohu.com", "Michael _ Sohu ", Charset), new internetaddress ("xyang0917@163.com", "_ 163", charset),}); // sets the CC message. setrecipient (recipienttype. CC, new internetaddress ("xyang0917@gmail.com", "Wang Wu _ Gmail", charset); // set BCC message. setrecipient (recipienttype. BCC, new internetaddress ("xyang0917@qq.com", "Zhao liu_qq", charset); // set the sending time message. setsentdate (new date (); // sets the recipient (the default recipient) message when the recipient replies to this email. setreplyto (internetaddress. parse ("\"" + Mimeutility. encodetext ("Tian Qi") + "\" <417067629@qq.com> "); // sets the priority (1: urgent 3: Normal 5: Low) message. setheader ("X-priority", "1"); // read receipt (the recipient will prompt to reply to the sender when reading the email, indicating that the email has been received and read) message. setheader ("disposition-Notification-to", from); // create a mimemultipart object with the mime subtype "mixed, indicates that this is a message of the hybrid combination type mimemultipart mailcontent = new mimemultipart ("mixed"); message. setcontent (mailcontent); // The attachment mimebodypart attach1 = new mimebodypart (); Mimebodypart attach2 = new mimebodypart (); // content mimebodypart mailbody = new mimebodypart (); // Add the attachment and content to the mail mailcontent. addbodypart (attach1); mailcontent. addbodypart (attach2); mailcontent. addbodypart (mailbody); // Appendix 1 (using the JAF framework to read the data source to generate the email body) datasource ds1 = new filedatasource ("resource/earth.bmp "); datahandler dh1 = new datahandler (ds1); attach1.setfilename (mimeutility. encodetext ("earth.bmp"); attach1.setdata Handler (dh1); // Annex 2 datasource ds2 = new filedatasource ("resource/ c.txt .txt"); datahandler DH2 = new datahandler (DS2); handler (DH2); attach2.setfilename (mimeutility. encodetext (" cc.txt .txt"); // The Mail body (Embedded Image + HTML text) mimemultipart body = new mimemultipart ("related"); // The Mail body is also a combination, you need to specify the combined link mailbody. setcontent (body); // The Mail body consists of HTML and images. mimebodypart imgpart = new mimebodypart (); mimebodypart htmlp Art = new mimebodypart (); body. addbodypart (imgpart); body. addbodypart (htmlpart); // body image datasource DS3 = new filedatasource ("resource/firefoxlogo.png"); datahandler DH3 = new datahandler (DS3); imgpart. setdatahandler (DH3); imgpart. setcontentid ("firefoxlogo.png"); // mimemultipart htmlmultipart = new mimemultipart ("alternative"); htmlpart. setcontent (htmlmultipart); mimebodypart htmlcontent = new mime Bodypart (); htmlcontent. setcontent ("<span style = 'color: red'> This is an email I sent using Java mail! "+"  </span> "," text/html; charset = GBK "); htmlmultipart. addbodypart (htmlcontent); // Save the email content and modify the message. savechanges ();/* file EML = buildemlfile (Message); sendmailforeml (EML); * // send the email transport. send (Message);}/*** generate the email content into an EML file * @ Param message the email content */public static file buildemlfile (message) throws messagingexception, filenotfoundexception, ioexception {file = new file ("C :\\" + mimeutility. decodetext (message. getsubject () + ". eml "); message. writeto (New fileoutputstream (File); Return file;}/*** send the locally generated email file */public static void sendmailforeml (File EML) throws exception {// get the mail session = session. getinstance (props, new myauthenticator (); // get the email content, that is, the EML file inputstream generated during the lifetime is = new fileinputstream (EML); mimemessage message = new mimemessage (Session, is); // send the email transport. send (Message);}/*** submit authentication information to the email server */static class myauthenticator extends authenticator {private string username = "xyang0917"; private string Password = "123456abc "; public myauthenticator () {super ();} public myauthenticator (string username, string password) {super (); this. username = username; this. password = PASSWORD ;}@ overrideprotected passwordauthentication getpasswordauthentication () {return New passwordauthentication (username, password );}}}

Test results:


1. Send a text email


2. Send simple HTML emails


3. Send HTML emails with embedded Images


4. Send a hybrid email combination

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.