Java Send mail

Source: Internet
Author: User
Tags html tags uuid

1. Install the required e-mail jar package

2. Send a simple e-mail

 PackageCom.mylight;Importjava.util.Properties;ImportJava.util.UUID;ImportJavax.mail.Authenticator;ImportJavax.mail.Message;Importjavax.mail.MessagingException;Importjavax.mail.PasswordAuthentication;Importjavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeMessage; Public classTestmail { Public Static voidMain (string[] args) {//recipient e-mailString to = "****@163.com"; //Sender e-mailString from = "* * * * @qq. com";    Senemail (to, from); }    Private Static voidSenemail (String to, string from) {//specifies that the host sending the message is smtp.qq.com          FinalString host = "smtp.163.com";//QQ Mail Server//Get System Properties          FinalProperties Properties =system.getproperties (); //setting up a mail serverProperties.setproperty ("Mail.smtp.host", host); Properties.put ("Mail.smtp.auth", "true"); //get the default Session object          FinalSession session = Session.getdefaultinstance (properties,NewAuthenticator () { Publicpasswordauthentication getpasswordauthentication () {return NewPasswordauthentication (From, "* * *");//Sender Mail user name, password (authorization password) and login password are different            }           }); Try{             //to create a default MimeMessage object             FinalMimeMessage message =NewMimeMessage (session); //Set from: Header fieldMessage.setfrom (Newinternetaddress (from)); //Set to: Header fieldMessage.addrecipient (Message.RecipientType.TO,Newinternetaddress (to)); //Set Subject: Head header fieldMessage.setsubject ("Verification Code")); //set the message bodyMessage.settext ("Your captcha is:" + string.valueof (Uuid.randomuuid ()). substring (0, 6). toUpperCase ()); //Send Messagetransport.send (message); System.out.println ("Sent Message successfully....from.com"); }Catch(FinalMessagingexception Mex)          {Mex.printstacktrace (); }    }}

3. Send an HTML email

 PackageCom.mylight;Importjava.util.Properties;ImportJavax.mail.Authenticator;ImportJavax.mail.Message;Importjavax.mail.MessagingException;Importjavax.mail.PasswordAuthentication;Importjavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeMessage; Public classHtmltestemail { Public Static voidMain (string[] args) {//recipient e-mailString to = "****@163.com"; //Sender e-mailString from = "****@163.com"; //specifies that the host sending the message is localhostString host = "Smtp.163.com"; //Get System PropertiesProperties Properties =system.getproperties (); //setting up a mail serverProperties.setproperty ("Mail.smtp.host", host); //Set up validationProperties.put ("Mail.smtp.auth", "true"); //Gets the default Session object. Session session = Session.getdefaultinstance (properties,NewAuthenticator () { Publicpasswordauthentication getpasswordauthentication () {return NewPasswordauthentication (From, "* * *");//Sender Mail user name, password                }        }); Try{             //creates a default MimeMessage object. MimeMessage message =NewMimeMessage (session); //Set from: Header fieldMessage.setfrom (Newinternetaddress (from)); //Set to: Header fieldmessage.addrecipient (Message.RecipientType.TO,Newinternetaddress (to)); //Set Subject: Header fieldMessage.setsubject ("This is the Subject line!"); //send HTML messages to insert HTML tagsMessage.setcontent (",                                "Text/html" ); //Send Messagetransport.send (message); System.out.println ("Sent message successfully ..."); }Catch(Messagingexception Mex) {mex.printstacktrace (); }    }}

4. Send an email with an attachment

 PackageCom.mylight;ImportJava.io.File;Importjava.util.Properties;ImportJavax.activation.DataHandler;ImportJavax.activation.DataSource;ImportJavax.activation.FileDataSource;ImportJavax.mail.Authenticator;ImportJavax.mail.BodyPart;ImportJavax.mail.Message;Importjavax.mail.MessagingException;ImportJavax.mail.Multipart;Importjavax.mail.PasswordAuthentication;Importjavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeBodyPart;ImportJavax.mail.internet.MimeMessage;ImportJavax.mail.internet.MimeMultipart; Public classFjtestemail { Public Static voidMain (string[] args) {//recipient e-mailString to = "****@163.com"; //Sender e-mailString from = "****@163.com"; //specifies that the host sending the message is localhostString host = "Smtp.163.com"; //Get System PropertiesProperties Properties =system.getproperties (); //setting up a mail serverProperties.setproperty ("Mail.smtp.host", host); //Set up validationProperties.put ("Mail.smtp.auth", "true"); //Gets the default Session object. Session session = Session.getdefaultinstance (properties,NewAuthenticator () { Publicpasswordauthentication getpasswordauthentication () {return NewPasswordauthentication (From, "lcy1992111");               }                      }); Try{             //creates a default MimeMessage object. MimeMessage message =NewMimeMessage (session); //Set from: Header fieldMessage.setfrom (Newinternetaddress (from)); //Set to: Header fieldmessage.addrecipient (Message.RecipientType.TO,Newinternetaddress (to)); //Set Subject: Header fieldMessage.setsubject ("This is the Subject line!"); //Create a message partBodyPart Messagebodypart =NewMimeBodyPart (); //messageMessagebodypart.settext ("This is message body"); //Creating multiple MessagesMultipart Multipart =NewMimemultipart (); //set text message partMultipart.addbodypart (Messagebodypart); //Accessories SectionMessagebodypart =NewMimeBodyPart (); //Path of attachments sentFile File =NewFile ("C:\\users\\sxcd\\desktop\\work\\codecommit.txt"); DataSource Source=Newfiledatasource (file); Messagebodypart.setdatahandler (NewDataHandler (source)); Messagebodypart.setfilename ("Code");                  Multipart.addbodypart (Messagebodypart); //Send Full Messagemessage.setcontent (multipart); //Send Messagetransport.send (message); System.out.println ("Sent message successfully ..."); }Catch(Messagingexception Mex) {mex.printstacktrace (); }    }}

Java Send mail

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.