First try javax. Mail

Source: Internet
Author: User
Tags imap

Recently, I used the mail sending function in my project. Since I have never touched on it before, I found a lot of information to finally get it out. I will write this article today to make a summary.
1. First define a mail data structure class
Public class emaildata (){
String from = NULL; // sender
String [] recipients = NULL; // recipient, which can contain multiple
String subject = NULL; // Email Subject
String content = NULL; // email content
String contenttype = NULL; // mail content format (text or HTML)
String filename = NULL; // File Name of the attachment (currently only one attachment is provided)

// The following is the corresponding setter/getter method, omitted ..
}
2. Send emails without attachments (including text and HTML)
Public void postmail (emaildata)
Throws messagingexception, exception {

String from = emaildata. getfrom ();
String [] recipients = emaildata. getrecipents ();
String subject = emaildata. getsubject ();
String content = emaildata. getcontent ();
String contenttype = emaildata. getcontenttype ();
String filename = emaildata. getfilename ();

If (recipients! = NULL & recipients. length> 0 ){

Properties props = new properties ();
// Set the email server address, connection timeout, and other information
Props. Put ("mail. SMTP. Host", "10.30.1.233"); // 10.30.1.233 email server
Props. Put ("mail. SMTP. connectiontimeout", "10000 ");//
Props. Put ("mail. SMTP. Timeout", "10000 ");//

// Create the default Session Object
Session session = session. getdefaultinstance (props, null );

// Create a message object
Message MSG = new mimemessage (session );

// Set the sender and recipient
Internetaddress addressfrom = new internetaddress (from );
MSG. setfrom (addressfrom );
Internetaddress [] addressto = new internetaddress [recipients. Length];
For (INT I = 0; I <recipients. length; I ++ ){
Addressto [I] = new internetaddress (recipients [I]);
}
MSG. setrecipients (message. recipienttype. To, addressto );

// Set the mail title and Chinese Encoding
Subject = mimeutility. encodetext (new string (subject. getbytes (), "gb2312"), "gb2312", "B ");
MSG. setsubject (subject );

// Set the mail content to distinguish text and HTML formats
If (contenttype = NULL | contenttype. Equals ("text ")){
MSG. settext (content );
} Else if (contenttype. Equals ("html ")){
// Set content for the message object
Bodypart bodypart1 = new mimebodypart (); // creates a bodypart object that stores the content of a letter.
MDP. setcontent (content, "text/html; charset = gb2312"); // set the content and format/encoding method for the bodypart object
Multipart MMP = new mimemultipart (); // create a new mimemultipart object to store bodypart objects (in fact, multiple objects can be stored)
// Set email attachments
Bodypart bodypart2 = new mimebodypart ();
Filedatasource = new filedatasource (filename );
Bodypart2.setdatahandler (New datahandler (filedatasource ));
Bodypart2.setfilename ("=? Gb2312? B? "+ Enc. encode (filename. getbytes () + "? = ");


Multipart = new mimemultipart ();
Multipart. addbodypart (bodypart1 );
Multipart. addbodypart (bodypart2 );

MMP. addbodypart (MDP); // Add the bodypart to the mimemultipart object (multiple bodyparts can be added)
MSG. setcontent (MMP); // use mm as the message object content
}

// Set the mail sending time
MSG. setsentdate (New java. util. Date ());
// Call the static method of abstract class send () to send an email
Transport. Send (MSG );
}
}

3. Sending emails with attachments is a little more complex. The differences between sending and sending common emails are as follows:
// Set the email content
Bodypart bodypart1 = new mimebodypart ();
Bodypart1.setdatahandler (New datahandler (New maildatasource (content, "text/html ")));

// Set email attachments
Bodypart bodypart2 = new mimebodypart ();
Filedatasource = new filedatasource (filename );
Bodypart2.setdatahandler (New datahandler (filedatasource ));
// The Name Of The attachment file must be transcoded. Otherwise, garbled characters may occur.
Bodypart2.setfilename ("=? Gb2312? B? "+ Enc. encode (filename. getbytes () + "? = ");

Multipart = new mimemultipart ();
Multipart. addbodypart (bodypart1 );
Multipart. addbodypart (bodypart2 );

// Add multipart to the mail
Newmessage. setcontent (multipart );

4. The following is a reprinted description of Java mail.
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
----------------------------------------------------------------
Once you create a session object, you must create a message to send the object. Message is an abstract class. In most applications, you can use its subclass javax. Mail. Internet. mimemessage. Mimemessage is a MIME type defined in different rfcs and the e-mail message & nbsp; 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 .");

For common text-type emails, there is a mechanism that is preferred for setting content (message. settext ("email content. If you want to create other types of messages, such as HTML-type messages, 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, you need to add an address to your email ). Like message, address is also an abstract class. We can use its 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 is also an abstract class. 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 a passwordauthentication instance. You must register your authenticator when the session is created. In this way, your authenticator can be obtained when authentication is required.

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, inbox is the only available folder. If IMAP is used, you can use other folders.

Reference: http://www.cnblogs.com/snoopy/articles/129932.html

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.