Preliminary Javax.mail

Source: Internet
Author: User
Tags auth imap

Turn from: http://blog.csdn.net/zhuyu_deng/article/details/12507545




Recently used in the project to send mail function, because has not been contacted before, find a lot of information to finally get it out, write these today, is to make a summary.
1, first define a mail data structure class
public class Emaildata () {
String from = null; Sender
string[] recipients = null; Recipients, you can multiple
String subject = NULL; Message subject
String content = null; Message content
String contentType = null; Message content Format (text or HTML)
String fileName = null; Attachment file name (only one attachment is currently available)

The following is the corresponding Setter/getter method, omitted.
}
2, send the message without attachments (including text format and HTML two formats)
public void Postmail (Emaildata 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 mail server address, connection timeout time, etc.
Props.put ("Mail.smtp.host", "10.30.1.233"); 10.30.1.233 Mail Server
Props.put ("Mail.smtp.connectiontimeout", "10000"); //
Props.put ("Mail.smtp.timeout", "10000"); //

Create a default Session object
Session session = Session.getdefaultinstance (props, null);

Create a Message Object
msg = new MimeMessage (session);

Setting up senders and recipients
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 Message title, Chinese encoding
Subject = Mimeutility.encodetext (New String (Subject.getbytes (), "GB2312"), "GB2312", "B");
Msg.setsubject (subject);

Set up message content, differentiate between text formatting and HTML formatting
if (ContentType = null | | contenttype.equals ("text")) {
Msg.settext (content);
else if (contenttype.equals ("html")) {
Set content for a Message object
BodyPart BodyPart1 = new MimeBodyPart (); Creates a new BodyPart object that holds the contents of a letter
Mdp.setcontent (Content, "text/html;charset=gb2312")//To BodyPart object set contents and Format/encoding method
Multipart MMP = new Mimemultipart ()//Create a new Mimemultipart object to hold the BodyPart object (in fact, you can store multiple)
Set up message Attachments
BodyPart bodyPart2 = new MimeBodyPart ();
Filedatasource Filedatasource = new Filedatasource (fileName);
Bodypart2.setdatahandler (New DataHandler (Filedatasource));
Bodypart2.setfilename ("=? GB2312? B? " +enc.encode (Filename.getbytes ()) + "? =");


Multipart Multipart = new Mimemultipart ();
Multipart.addbodypart (BODYPART1);
Multipart.addbodypart (BODYPART2);

Mmp.addbodypart (MDP)//Add BodyPart to Mimemultipart object (multiple bodypart can be added)
Msg.setcontent (MMP);//mm as the content of the Message object
}

Set the time to send messages
Msg.setsentdate (New Java.util.Date ());
Calling static method Send () of an abstract class sends a message
Transport.send (msg);
}
}

3, send the message with the attachment a little more complex, with the main difference between sending ordinary mail is as follows:
Set up message content
BodyPart BodyPart1 = new MimeBodyPart ();
Bodypart1.setdatahandler (New DataHandler (content, "text/html"));

Set up message Attachments
BodyPart bodyPart2 = new MimeBodyPart ();
Filedatasource Filedatasource = new Filedatasource (fileName);
Bodypart2.setdatahandler (New DataHandler (Filedatasource));
The name of the attachment file needs to be transcoding, or there will be garbled
Bodypart2.setfilename ("=? GB2312? B? " +enc.encode (Filename.getbytes ()) + "? =");

Multipart Multipart = new Mimemultipart ();
Multipart.addbodypart (BODYPART1);
Multipart.addbodypart (BODYPART2); Add multipart to the letter
Newmessage.setcontent (multipart);

4, the following is reproduced on the Java Mail introduction
Session
--------------------------------------------------------------------
The session defines a basic mail conversation, and any work is based on the sessions. The session object needs a Java.util.Properties object to get information like a mail server, username, password, and so on.

The session constructor is private, and you can use the Getdefaultinstance () method to obtain a single default session that can be shared:

Properties Props = new properties ();
Fill in some information
Session session = Session.getdefaultinstance (props,null);

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

Properties Props = new properties ();
Fill in some information
Session session = Session.getinstance (props,null);

The null parameter in both methods is a authenticator object, which is not used here, so it is null

In most cases, it's enough to use a shared session.

Message
----------------------------------------------------------------
Once you create the session object, the next thing to do is to create a message to send. Message is an abstract class, and in most applications you can use its subclass javax.mail.internet.MimeMessage. MimeMessage is an e-mail message&nbsp; that understands the MIME types defined in different RFCs and headers. Message headers must use the US-ASCII character set.

You can create a message by using the following method
MimeMessage message = new MimeMessage (session);
We notice that we need to use the session object as a parameter to the constructor. Of course, there are other constructors, such as creating a message from an input stream formatted with RFC822.

Once you get the message, you can set the various parts of it (parts). The basic mechanism for setting content is to use the SetContent () method.

Message.setcontent ("Email Content.", "Text/plain");

If you can express your use of mimemessage to create a message and just use plain text (plain text), you can also use the SetText () method, Settest () method to set the specific content, the default MIME type is Text/plain

Message.settext ("Email Content.");

For ordinary text-type messages, one mechanism is preferred (Message.settext ("Email Content.") The method of setting the content. If you want to create other types of message, such as HTML type message, then you need to use the former (Message.setcontent ("Email Content.", "text/html"); )

Set the theme (subject), using the Setsubject () method

Message.setsubject ("Subject");

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

When you have created the session and message and have filled it with messages, the next thing to do is to add an address to your email. Like the message, the address is an abstract class, and we can use a subclass of it to javax.mail.internet.InternetAddress.

Creating an address is very simple

Address = new InternetAddress ("suixin@asiainfo.com");

If you want a name to appear where the e-mail address appears, you only need to pass one more argument.

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 the Setreplyto () method.

Messge.setfrom (address);

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

Address 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 requires a message.recipienttype.

Message.addrecipient (type,address);

Message.recipienttype has several predefined types

Message.RecipientType.TO Recipients
Message.RecipientType.CC cc
Message.RecipientType.BCC Dark Send

If you have an email that needs to be sent to your teacher and also to some of your classmates, then 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 detection of the validity of e-mail addresses. These transcend the scope of the JavaMail API.

Authenticator

By authenticator set user name, password, to access the protected resources, where the resources generally refers to the mail server.

Authenticator is also an abstract class, and you need to write subclasses of your own to be ready to apply. You need to implement the Getpasswordauthentication () method and return a passwordauthentication instance. You must register your authenticator when the session is created. This way, when you need to be authenticated, your authenticator can be obtained.

Properties Props = new properties ();
Setting properties
Authenticator auth = new Yourauthenticator ();
Session session = Session.getdefaultinstance (props, auth);

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

The last step in sending a message is to use the transport class, which you can send in two different ways.
Transport is an abstract class that 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 are using,

Transport transport = Session.gettransport ("SMTP");
Transport.sendmessage (Message, message.getallrecipients ());
Transport.close ();

Store and Folder

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

Store 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 open.

Folder folder = Store.getfolder ("INBOX");
Folder.open (folder.read_only);
Message message[] = Folder.getmessages ();

If you use POP3, index is the only folder available. If you are using IMAP, you can use a different folder.

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.