Java mail Introduction

Source: Internet
Author: User

This document consists of three parts: The first part briefly introduces javamail, the second part is the introduction of several key classes of javamail, And the last part is a small program for sending emails. The introduction of several core classes is basically a document about javamail translated by IBM. I hope to help you.

[@ More @] At the beginning, it is really nice to use javamail to send and receive emails (because it is very simple :).

No
Whether you send or receive emails, the first thing is to create a session. If you are sending an email, then you need to create the email you want to send, that is, a message
Object. The current message object seems to be blank. Now we need to add the content. Message. setcontent () can help you solve the problem. Then we need to write a "letter
"Message. setfrom (); message. addrecipient ();...
Haha, everything is done, and then you can send it out.
Transport transport = session. gettransport ("SMTP ");
Transport. sendmessage (message, message. getallrecipients ());
Transport. Close ();

Good
Yes, the email has been sent. :) of course, this is too optimistic. We have encountered other problems during the sending process, such as authentication and address. Below are some important points about javamail.
(This article mainly translated a document about javamail from IBM developerworks and added some personal opinions)

========================================================== ======================================

Session
--------------------------------------------------------------------
A session defines a basic mail session. All work is based on this session. The Session object requires a java. util. properties object to obtain information such as the email server, user name, and password.

The session constructor is private. You can use the getdefainstance instance () method to obtain a single default session that can be shared, for example:

Properties props = new properties ();
// Enter some information
Session session = session. getdefaultinstance (props, null );

Alternatively, you can use the getinstance () method to create a unique session, for example:

Properties props = new properties ();
// Enter some information
Session session = session. getinstance (props, null );

In the two methods, the null parameter is an authenticator object, which is not used here, so it is null.

In most cases, using a shared session is enough.

Message
----------------------------------------------------------------
I
Once you have created a session object, the following is to create a message for sending. Message is an abstract class. In most applications, you can use its sub-class
Class javax. Mail. Internet. mimemessage. Mimemessage is a MIME type that is understood in different rfcs and
The e-mail message of headers. Message Headers must use the US-ASCII character set.

You can use the following method to create a message
Mimemessage message = new mimemessage (session );
We noticed that the session object must be used as the constructor parameter. Of course, there are other constructor functions, such as creating a message from an input stream formatted with rfc822.

Once you get the message, you can set its parts (parts ). The basic mechanism for setting content is to use the setcontent () method.

Message. setcontent ("email content.", "text/plain ");

If you can explicitly use mimemessage to create a message and only use plain text (plain text), you can also use the settext () method, settest () you only need to set specific content. The default MIME type is text/plain.

Message. settext ("email content .");

Pair
For normal text-type emails, there is a mechanism that is preferred for setting content (message. settext ("email content. If you want to create another
Type message, such as HTML type message, you still need to use the former (
Message. setcontent ("email content.", "text/html ");)

Set the topic (subject) and use the setsubject () method.

Message. setsubject ("subject ");

Address
----------------------------------------------------------------

When
You have created a session and message and filled the message with content. The next step is to add an address to your email.
(Address ). Like message, address is also an abstract class. We can use it as a subclass.
Javax. Mail. Internet. internetaddress.

Creating an address is simple.

Address = new internetaddress ("
Suixin@asiainfo.com

");

If you want a name to appear in the email address, you only need to pass another parameter.

Address = new internetaddress ("
Suixin@asiainfo.com

"," Steve ");

You need to create an address object for the from and to fields of the message. To identify the sender, you need to use the setfrom () and setreplyto () methods.

Messge. setfrom (Address );

If your message needs to display multiple from addresses, you can use the addfrom () method.

Address [] = {....};
Message. addfrom (Address );

To identify the recipient of the message, you need to use the setrecipient () method. In addition to the address parameter, This method also requires a message. recipienttype.

Message. addrecipient (type, address );

Message. recipienttype has several predefined types.

Message. recipienttype. to recipient
Message. recipienttype. CC
Message. recipienttype. bcc

If you need to send an email to your teacher and several other students, you can

Address toaddress = new internetaddress ("
Teacher@17288.com

");
Address [] ccaddress = {New internetaddress ("
Schoolmate1@17288.com

"), New internetaddress ("
Schoolmate2@17288.com

")};

Message. addrecipient (message. recipienttype. To, toaddress );
Message. addrecipient (message. recipienttype. CC, ccaddress );

Javamail does not provide an email address validity check. These are beyond the scope of the javamail API.

Authenticator

Use authenticator to set the user name and password to access protected resources. The resources here generally refer to the mail server.

Authenticator
It is also an abstract class, and you need to write your own child classes that have been applied by the slave class. You need to implement the getpasswordauthentication () method and return
Passwordauthentication instance. You must register your authenticator when the session is created. In this way, when authentication is required
Yes, your authenticator will be available.

Properties props = new properties ();
// Set attributes
Authenticator auth = new yourauthenticator ();
Session session = session. getdefaultinstance (props, auth );

Transport
----------------------------------------------------------------

The last step to send a message is to use the transport class. You can send the message in two ways.
Transport is an abstract class. You can call its static send () method to send

Transport. Send (Message );

Alternatively, you can obtain a specified instance from the session for the protocol you use,

Transport transport = session. gettransport ("SMTP ");
Transport. sendmessage (message, message. getallrecipients ());
Transport. Close ();

Store and folder

These two classes are important for obtaining information. After creating a session, you need to connect to a store. You need to tell the store what protocol you are using.

// Store = session. getstore ("IMAP ");
Store store = session. getstore ("POP3 ");
Store. Connect (host, username, password );

After connecting to a store, you can get a folder. Of course, this floder must be enabled.

Folder folder = store. getfolder ("inbox ");
Folder. Open (Folder. read_only );
Message message [] = folder. getmessages ();

If POP3 is used, index is the only available folder. If IMAP is used, you can use other folders.

========================================================== ======================================

The following is an example of sending an email.

Sendmailauthenticator
---------------------------------------
Package com. Steve. Email;

Import javax. Mail. authenticator;
Import javax. Mail. passwordauthentication;

Public class sendmailauthenticator extends authenticator {
Private string username = "";
Private string Password = "";

Public void check (string username, string password ){
This. Username = username;
This. Password = password;
}

Public passwordauthentication getpasswordauthentication (){
Return new passwordauthentication (username, password );
}
}

Sendmailtools
--------------------------------------------------------
Package com. Steve. Email;

Import java. util. properties;
Import java. util. date;
Import javax. Mail .*;
Import javax. Mail. Internet .*;

Public class sendmailtools {

Public static void main (string [] ARGs ){

Properties props = new properties ();

Sendmailauthenticator Au = new sendmailauthenticator ();
Au. Check ("*******", "*******"); // authentication (user name and password)
Props. Put ("mail. SMTP. Host", "smtp.17288.com"); // set the SMTP server
Props. Put ("mail. SMTP. Auth", "true"); // This way the authentication will take effect :)
Session session = session. getinstance (props, AU); // create a session

Mimemessage message = new mimemessage (session); // creates a message object
// Write an "envelope" first
Try {
Address = new internetaddress ("
Sender@17288.com

"," Steve "); // sender address
Address toaddress = new internetaddress ("
Getter@asiainfo.com

"); // Recipient address
Message. setfrom (Address); // sets the sender
Message. setrecipient (mimemessage. recipienttype. To, toaddress); // set the recipient

// Enter the email content below
Message. setsubject ("test email", "gb2312"); // set the topic
Message. setsentdate (new date (); // you can specify a date.
Message. settext ("test mail", "gb2312"); // set the mail content

// Sent
Transport transport = session. gettransport ("SMTP ");
Transport. Send (Message );

} Catch (exception ex) {// Hey, this is the case for simplicity. This is not worth advocating :)
}
}
}

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.