Java Send email

Source: Internet
Author: User

Using Java application to send e-mail is very simple, the following main demo, send ordinary email. Send an HTML-type email, and send an email with an attachment.


First, configure the required jar package

We need to add the Mail.jar and Activation.jar two jar packages to our classpath. You can download the latest version number in the JavaMail API and JAF (Javaactivation Framework). For example, with:


  


Second, send a regular email

First we simply encapsulate a tool class that sends messages. In addition, we intend to use the QQ mail server to send e-mail, this need to authenticate the sender, the urgent need to verify the sender's username, password, so we have defined an authentication class.

Then write a test class and you can test it. The demo sample code is as follows:

2.1 tool classes for sending messages
public class Sendeasyemailtomanypeople {public static void SendEmail (string[] toaddress, String fromaddress, String HostA Ddress, String subject, String MessageText) throws Exception {//recipient e-mail "can have multiple recipients" internetaddress[] sendTo = new Interneta ddress[toaddress.length];for (int i = 0; i < toaddress.length; i++) {System.out.println ("Send to:" + toaddress[i]); sendto[ I] = new internetaddress (Toaddress[i]);} Sender e-mail string from = fromaddress;//Specifies the host that sent the message string host = hostaddress;//Gets the System Property properties Properties = System.getprope Rties ();//Set Mail Serverproperties.setproperty ("Mail.smtp.host", host);p roperties.put ("Mail.smtp.auth", "true"); This ability is verified by myauthenticator Myauth = new Myauthenticator ("Your email address", "Your Mailbox password");//Gets the default Session object Session session = Session.getdefaultinstance (properties, Myauth); try {//create default MimeMessage object MimeMessage message = new MimeMessage ( session);//Set from: Head Header field Message.setfrom (New InternetAddress (from));//Set to: Head Header field (type: To be set to, CC, or Bcc). CC represents CC, BCC for secret cc y.// Example: Message.RecipientType.TO) message.addrecipients (Message.RecipientType.TO, sendTo);//Set Subject: Header field Message.setsubject (subject);//Set Message body Message.settext (messagetext);//Send Message transport.send (message); SYSTEM.OUT.PRINTLN ("Sent message successfully ...."); catch (Messagingexception Mex) {mex.printstacktrace ();}}}

2.2 Authentication Classes
/** * Sender Permission Check class *  * @author Wangzhipeng *  */public class Myauthenticator extends Javax.mail.Authenticator {private String Struser;private string Strpwd;public myauthenticator (string user, string password) {This.struser = USER;THIS.STRP WD = password;} Protected Passwordauthentication getpasswordauthentication () {return new passwordauthentication (struser, STRPWD);}}

2.3 Test Class
/** * Test class for sending normal mail *  * @author Wangzhipeng *  */public class Testsendemailtomanypeople {public static void main (Strin G[] args) throws Exception {//Recipient Mailbox "multiple recipients" string[] toaddress = new string[] {"[email protected]", "[email protected]", " [Email protected] "};//Sender mailbox String fromaddress =" your email address ";//mail server type (here is QQ, assuming 163 is" smtp.163.com ") string hostaddress = "smtp.qq.com";//the subject of the message string subject = "Test mail--java";//The Body of the message string MessageText = "Hello world Asidifen";//Send mail SE Ndeasyemailtomanypeople.sendemail (toaddress, fromaddress, hostaddress, subject, MessageText);}}

2.4 Test Results

Three people receive mail at the same time, for example by:

  

The contents are as follows:

  


third, send HTML type email

Almost like the previous example, we just need to use the SetContent () method in the "Send Mail Tool class" above to set the content to specify that you want to send HTML content by using the second parameter "text/html", for example:

  


Test Results  


Iv. sending an email with attachments

For example, we send a file.txt file under the root folder of our project as an attachment to the message:

  

We need to change our "tool class" and "Test class" on the basis of "send normal email", the authentication class does not change, the demo sample code is as follows:

4.1 Tool Classes
public class Sendfileemail {public static void SendEmail (String toaddress, String fromaddress, String hostaddress, String Subject, String MessageText, String filerealpath) {//Recipient email string to = toaddress;//Sender e-mail string from = fromaddress;// Specifies the host that sent the message string host = hostaddress;//Gets the System Property Properties Properties = System.getproperties ();// Set the message Serverproperties.setproperty ("Mail.smtp.host", host);p roperties.put ("Mail.smtp.auth", "true"); This ability is verified by myauthenticator Myauth = new Myauthenticator ("Your email address", "Your Mailbox password");//Gets the default Session object Session session = Session.getdefaultinstance (properties, Myauth); try {//create default MimeMessage object MimeMessage message = new MimeMessage ( session);//Set from: Head Header field Message.setfrom (New InternetAddress (from));//Set to: Head Header field Message.addrecipient ( Message.RecipientType.TO, New InternetAddress (To)),//Set Subject: Head header field Message.setsubject (Subject);//------------- -----------------------------------------------------------------------------//Create message section BodyPart Messagebodypart= new MimeBodyPart ();//Message Messagebodypart.settext (MessageText);//Create multiple messages multipart multipart = new Mimemultipart ();// Set text message part Multipart.addbodypart (messagebodypart);//Accessory Part Messagebodypart = new MimeBodyPart (); String filename = filerealpath;//Gets the attachment physical path DataSource Source = new Filedatasource (filename); Messagebodypart.setdatahandler (new DataHandler); messagebodypart.setfilename (filename); Multipart.addbodypart (Messagebodypart);//Send Full message message.setcontent (multipart);//------------------------------- -----------------------------------------------------------//Send messages Transport.send (message); SYSTEM.OUT.PRINTLN ("Sent message successfully ...."); catch (Messagingexception Mex) {mex.printstacktrace ();}}}

4.2 Test Class
public class Testsendfileemail {public static void main (string[] args) {//recipient mailbox String toaddress = "[email protected]";// Sender Mailbox String fromaddress = "your email address";//mail server type (here is QQ.) Suppose you want to use 163 for "smtp.163.com") string hostaddress = "smtp.qq.com";//the subject of the message string subject = "Test mail--java";//Message body string MessageText = "Hello world!

。。 ";//Get file absolute path string projectpath = System.getproperty (" User.dir "); String Filerealpath = projectpath.replace ("\ \", "/") + "/file.txt";//Send mail Sendfileemail.sendemail (toaddress, Fromaddress, hostaddress, subject, MessageText, Filerealpath);}}


4.3 test results  

v. Summary

When using mail server such as QQ, 163, Sohu, Yahoo. We must first send the message through the corresponding email server's authentication talent to prevent others from hair the message at will.

Of course, some mail service systems do not need to verify the authorization of the sender. So can in enterprises and institutions in the internal e-mail system very easy to use, such as. We changed the outgoing Mail tool class to instantiate the session process, such as the following:

  

This allows you to omit the following code (and authentication classes):

  

Java Send email

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.