Java Send email

Source: Internet
Author: User
Tags email string

Using Java applications to send e-mail is very simple, the following main demo, send ordinary email, send HTML type of email, send an email with attachments.


First, configure the required jar package

We need to add the Mail.jar and Activation.jar two jar packages to our classpath, and you can download the latest version in the JavaMail API and JAF (Javaactivation Framework). Such as:


  


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 need to verify the sender's user name, password, so we define an authentication class. Then write a test class to test. The 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 server Properties.setproperty ("Mail.smtp.host", host);p roperties.put ("Mail.smtp.auth", "true"); This can be verified by myauthenticator Myauth = new Myauthenticator ("Your email address", "your email password");//Get 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). Here cc represents CC, BCC on behalf of the secret cc y.//example: MessaGe. recipienttype.to) message.addrecipients (Message.RecipientType.TO, sendTo);//Set Subject: Head header field Message.setsubject ( subject);//Set Message body Message.settext (messagetext);//Send Message Transport.send (messages); 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, if you want to use 163" smtp.163.com ") string hostaddress = "smtp.qq.com";//the subject of the message string subject = "test message--java";//The Body of the message string MessageText = "Hello world Asidifen";//Send mail Sendeasyemail Tomanypeople.sendemail (toaddress, fromaddress, hostaddress, subject, MessageText);}}

2.4 Test Results

Three people are also subject to mail, such as:

  

The contents are as follows:

  


third, send HTML type email

Almost like the previous example, we only need to use the SetContent () method in the "Send Mail Tool class" above to specify the content to be sent by using the second parameter "text/html", such as:

  


Test Results  


Iv. sending an email with attachments

For example, we send a file.txt file in the root directory 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 will not change, the 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 mail server Properties.setproperty ("Mail.smtp.host", host);p roperties.put ("Mail.smtp.auth", "true"); This can be verified by myauthenticator Myauth = new Myauthenticator ("Your email address", "your email password");//Get 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 part 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, if you want to use 163 "smtp.163.com") String hostaddress = "smtp.qq.com";// The subject of the message string subject = "test message--java";//The Body of the message 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 servers like QQ, 163, Sohu, Yahoo, etc., we must first pass the corresponding mail server authentication to send the mail, to prevent others from arbitrarily hair the message.

Of course, some mail service system does not need to verify the sender's authorization, so can be in enterprises and institutions of internal e-mail system is very simple to use, for example, we change the email tool class to instantiate the session process, as follows:

  

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

  

Java Send email

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.