Java Mail and Apache Mail send mail sample _java

Source: Internet
Author: User

First, the mail introduction

A message is composed of a lot of information, the main information is as follows, the other temporarily do not consider, such as CC, etc.:

1, the recipient: The recipient's e-mail address, such as xxx@xx.com

2, the recipient's name: Most of the mail will display, such as Loadfate 779554589@qq.com

3. Sender: Email address of sender

4. Name of sender:

5, Subject: the title of the message

6, Content and accessories: The main content of the mail

Ii. common steps for using Java to send mail

In general, there are no separate mail servers in the project, usually using someone else's server.

1, set up SMTP server: Different mail servers have different addresses, for example: Smtp.qq.com means Tencent's SMTP server.

2, Authorization: Use the server's account number and password to log on to the server.

3, create a message: Create a message containing all the information, such as senders, recipients, content and so on.

4, set the properties of the message: To add data for the properties of the message.

5, send mail: Because the package is different, the way to send inconsistent.

Third, Java Mail and Apache Mail

Apache Mail is a package for Java mail that is simpler to use and has a better sense of logic.

Only one jar package needs to be imported using Java Mail: Mail.jar.

You need to import two jar packages when using Apache Mail: Mail.jar, Commons-email-1.3.1.jar.

Iv. use Java mail to send mail

Copy Code code as follows:

public static void Main (string[] args) throws Exception {
Final String user = "779554589";
Final String password = "";
String fromaddress = "779554589@qq.com";
String toaddress = "loadfate@163.com";
String subject = "message test subject";
String content = "This is a test email <b> haha </b>";
Configuration parameters
Properties Props = new properties ();
Props.setproperty ("Mail.smtp.auth", "true");
Props.setproperty ("Mail.transport.protocol", "SMTP");
Props.setproperty ("Mail.host", "smtp.qq.com");
Method One: Send a message using the transport object
{
To generate a session from a parameter
Session session = Session.getinstance (props);
Enable debug mode
Session.setdebug (TRUE);
Create a message and set the information
Message message = new MimeMessage (session);
Message.setfrom (New InternetAddress (fromaddress));
Message.setsubject (subject);
Message.settext (content);
Create a transport
Transport transport = Session.gettransport ();
Connecting to an SMTP server
Transport.connect (user, password);
Send
Transport.sendmessage (message, new internetaddress[] {new internetaddress (toaddress)});
Transport.close ();
}
Method Two: Send a message using the Transport class static method
{
To obtain an authorized connection when session is generated
Session session = Session.getinstance (props, New authenticator () {
@Override
Protected Passwordauthentication getpasswordauthentication () {
return new passwordauthentication (user, password);
}
});
Session.setdebug (TRUE);
Create a message and set the information
Message message = new MimeMessage (session);
Message.setsubject (subject);
Message.setfrom (New InternetAddress (fromaddress));
Message.setrecipient (recipienttype.to, New InternetAddress (toaddress));
Message.setcontent (Content, "text/html;charset=utf-8");
Send directly, message is generated through a session that has been authorized
Transport.send (message);
}
}

V. Send mail using Apache Mail

Copy Code code as follows:

public class Apachemailtest {
SMTP server
Private String HostName = "smtp.qq.com";
Account number and password
Private String UserName = "779554589";
Private String Password = "This is a secret";
Sender
Private String fromaddress = "779554589@qq.com";
Sender Name
Private String FromName = "Loadfate";
public static void Main (string[] args) throws Exception {
Recipient and recipient Name
String toaddress = "loadfate@163.com";
String toname = "Loadfate";
Apachemailtest test = new Apachemailtest ();
All the exceptions are handled for easy browsing.
Test.sendsimpleemail (toaddress, ToName);
Test.sendhtmlemail (toaddress, ToName);
Test.sendmultipartemail (toaddress, ToName);
SYSTEM.OUT.PRINTLN ("Send Complete");
}
Send a simple message, similar to a piece of information
public void Sendsimpleemail (string toaddress, String toname) throws Exception {
Simpleemail email = new Simpleemail ();
Email.sethostname (hostName);//Set up SMTP server
Email.setauthentication (userName, password)//Set licensing information
Email.setcharset ("Utf-8");
Email.setfrom (fromaddress, FromName, "utf-8");/Set Sender information
Email.addto (toaddress, ToName, "utf-8");/Set Recipient information
Email.setsubject ("test subject");/Set Theme
Email.setmsg ("This is a simple test!") ");/set the content of the message
Email.send ()//Send mail
}
Messages that send HTML content
public void Sendhtmlemail (string toaddress, String toname) throws Exception {
Htmlemail email = new Htmlemail ();
Email.sethostname (HostName);
Email.setauthentication (userName, password);
Email.setcharset ("Utf-8");
Email.addto (toaddress, ToName, "utf-8");
Email.setfrom (fromaddress, FromName, "utf-8");
Email.setsubject ("This is an HTML message");
Set HTML content that you can read from text to write HTML code when you actually use it
Email.sethtmlmsg ("<div style= ' width:100px;height:200px;") >a</div> ");
Email.send ();
}
Send complex messages, include attachments, etc.
public void Sendmultipartemail (string toaddress, String toname) throws Exception {
Multipartemail email = null;
email = new Multipartemail ();
Email.sethostname (HostName);
Email.setauthentication (userName, password);
Email.setcharset ("Utf-8");
Email.addto (toaddress, ToName, "utf-8");
Email.setfrom (fromaddress, FromName, "utf-8");
Email.setsubject ("This is a mail with attachments");
Email.setmsg ("<a href= ' > Test Content </a>");
Add additional content to a message
Emailattachment attachment = new Emailattachment ();
Attachment.setpath ("d:\\ Mail. txt");//local file
Attachment.seturl (New URL ("Http://xxx/a.gif"))//remote file
Attachment.setdisposition (emailattachment.attachment);
Attachment.setdescription ("Descriptive Information");
Set the attachment display name, must be coded, otherwise Chinese will be garbled
Attachment.setname (mimeutility.encodetext ("message txt"));
Add an attachment to a message
Email.attach (attachment);
Email.send ();
}
}


VI. Annexes
Project folder: Maildemo

Download Address: Http://pan.baidu.com/s/1bn1Y6BX

If you have any questions or suggestions, please contact me

File Description:

1, the source code of Maildemo.zip:maildemo

2, Mail.jar:Java mail jar package

3, Commons-email-1.3.1.jar:apache mail jar package

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.