Java Mail (3): Session and Message Details

Source: Internet
Author: User
Tags imap

This article is from: Gao Shuang | Coder. The original Article address is http://blog.csdn.net/ghsau/article/details/17909093. For more information, see.
The previous article introduced JavaMail and implemented a simple example of sending emails. JavaMail API is very flexible to use. For example, server information can be set to Session or Transport, the recipient can be set to Message or Transport. How to Use it depends on the actual situation in our application. This article describes in detail the main methods of these three classes.

Session
Session is used to collect environment information during JavaMail running. It can create a singleton object or create a new object each time. The Session has no constructor and can only create instances using the following method:
static Session getDefaultInstance(Properties props)
Get the default Session object.
static Session getDefaultInstance(Properties props,Authenticator authenticator)
Get the default Session object.
static Session getInstance(Properties props)
Get a new Session object.
static Session getInstance(Properties props,Authenticator authenticator)
Get a new Session object.
GetDefaultInstance always gets the default object created for the first time by the method, while getInstance always gets the new object. The use of Authenticator will be discussed later. You can create Transport (for sending mails) and Store (for receiving mails) through Session. Transport and Store are the interfaces defined in JavaMail API, through the above, we know that JavaMail is divided into two parts: API and service provider. The API defines related interfaces (eg.: Transport and Store), service provider implements these interfaces, these Implementation classes are configured in Javamail. providersOr Javamail. default. providersIn the mail. jar/smtp. jar/pop3.jar/imap. jar META-INF, the file content format is as follows:
# JavaMail IMAP provider Sun Microsystems, Incprotocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Sun Microsystems, Inc;protocol=imaps; type=store; class=com.sun.mail.imap.IMAPSSLStore; vendor=Sun Microsystems, Inc;# JavaMail SMTP provider Sun Microsystems, Incprotocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc;protocol=smtps; type=transport; class=com.sun.mail.smtp.SMTPSSLTransport; vendor=Sun Microsystems, Inc;# JavaMail POP3 provider Sun Microsystems, Incprotocol=pop3; type=store; class=com.sun.mail.pop3.POP3Store; vendor=Sun Microsystems, Inc;protocol=pop3s; type=store; class=com.sun.mail.pop3.POP3SSLStore; vendor=Sun Microsystems, Inc;
Each line declares the protocol name, type, implementation class, supplier, version, and other information. If you need to implement the corresponding protocol yourself, you must configure it in this format, java Mail API can be called correctly. The methods for creating Trasnsport and Store in Session are as follows:
Store getStore()
Get a Store object that implements this user's desired Store protocol.
Store getStore(Provider provider)
Get an instance of the store specified by Provider.
Store getStore(String protocol)
Get a Store object that implements the specified protocol.
Store getStore(URLName url)
Get a Store object for the given URLName.
Transport getTransport()
Get a Transport object that implements this user's desired Transport protcol.
Transport getTransport(Address address)
Get a Transport object that can transport a Message of the specified address type.
Transport getTransport(Provider provider)
Get an instance of the transport specified in the Provider.
Transport getTransport(String protocol)
Get a Transport object that implements the specified protocol.
Transport getTransport(URLName url)
Get a Transport object for the given URLName.
As you can see, there are a lot of refactoring, and these methods will eventually parse the configuration file mentioned above and find the corresponding configuration information.
Message
Message is the carrier of the mail, used to encapsulate all information of the mail. Message is an abstract class. Known implementation classes include MimeMessage. What information does a complete email contain? Open an email client. I use FoxMail to create an email, as shown in:
This is all the information contained in a complete email. By default, no sending or reply settings are provided, you can use the menu bar --> View --> dark send address/reply address to display the reply address. By default, the reply address is the sender, and dark send is a relatively cumbersome method of sending emails, in addition to the recipient, no one knows who the recipient is. The email header information is not recorded. The following describes how to set Mail Information in Message. Sender
abstract void setFrom()
Set the "From" attribute in this Message.
abstract void setFrom(Address address)
Set the "From" attribute in this Message.
Currently, most SMTP servers require the sender to be consistent with the connected account; otherwise, an exception of verification failure will be thrown to prevent the user from maliciously sending emails as another account. Recipient/CC/hidden recipient
void setRecipient(Message.RecipientType type,Address address)
Set the recipient address.
abstract void setRecipients(Message.RecipientType type,Address[] addresses)
Set the recipient addresses.
The first method is set to individual, and the second method is set to multiple individuals. The first parameter in the method involves another class RecipientType, which is the static internal class of Message and has three constant values in the period:
static Message.RecipientType BCC
The "Bcc" (blind carbon copy) recipients.
static Message.RecipientType CC
The "Cc" (carbon copy) recipients.
static Message.RecipientType TO
The "To" (primary) recipients.
TO-recipient, CC-CC, and BCC-BCC. Reply
void setReplyTo(Address[] addresses)
Set the addresses to which replies shocould be directed.
Set the reply address after the recipient receives the email. Title
abstract void setSubject(String subject)
Set the subject of this message.
Set the mail title/subject. Content
void setContent(Multipart mp)
This method sets the given Multipart object as this message's content.
void setContent(Object obj,String type)
A convenience method for setting this part's content.
void setText(String text)
A convenience method that sets the given String as this part's content with a MIME type of "text/plain ".
Set the mail text content, HTML content, and attachment content.
Example
Here is an example of a slightly complex point:
Public class JavaMailTest2 {public static void main (String [] args) throws MessagingException {Properties props = new Properties (); // enable debug debugging props. setProperty ("mail. debug "," true "); // The sender server requires authentication props. setProperty ("mail. smtp. auth "," true "); // set the mail server host name props. setProperty ("mail. host "," smtp.163.com "); // mail protocol name props. setProperty ("mail. transport. protocol "," smtp "); // sets the environment information Session = session. getInstance (props, new Authenticator () {// Set account information in session. When Transport sends an email, it uses protected PasswordAuthentication getPasswordAuthentication () {return new PasswordAuthentication ("java_mail_001 ", "javamail") ;}}); // create the email object Message msg = new MimeMessage (session); // sender msg. setFrom (new InternetAddress ("java_mail_001@163.com"); // multiple recipients msg. setRecipients (RecipientType. TO, InternetAddress. parse ("java_mail_002@163.com, java_mail_003@163.com"); // CC to msg. setRecipient (RecipientType. CC, new InternetAddress ("java_mail_001@163.com"); // secretly send msg. setRecipient (RecipientType. BCC, new InternetAddress ("java_mail_004@163.com"); // topic msg. setSubject ("Chinese topic"); // HTML content msg. setContent ("hello", "text/html; charset = UTF-8"); // connects to the mail server, sends emails, and closes connections, all of which are Transport. send (msg );}}
This article is from: Gao Shuang | Coder. The original Article address is http://blog.csdn.net/ghsau/article/details/17909093. For more information, see.

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.