Knowledge about the application layer e-mail service and javaMail mail sending, and javamail mail sending

Source: Internet
Author: User
Tags imap email protocols

Knowledge about the application layer e-mail service and javaMail mail sending, and javamail mail sending
What do you need to know about the Email service: Overview:

Today, we will introduce the application-layer email service, which we use almost every day. The email service is also a service based on the C/S model, it uses a "Storage-forwarding" service, which is a service of asynchronous communication and can perform non-real-time communication.

The entire email system includes two parts: "User proxy" (UA) and "message transmission proxy" (MTA.

    User Agent (UA): Provides the user with an operation interface located in the client host.

    Information Transmission proxy (MTA): Responsible for message transmission, the so-called "email Post Office", which is generally located in the mail server.

Common email protocols:

The standard for sending and receiving emails must be observed. There are three common email protocols:

SMTP (Simple Mail Transfer Protocol): provides the email sending service. Port number 25.

POP3 (Post Office Protocol 3): provides mail acceptance services. Port Number 110;

IMAP (Internet Message Access Protocol): a more powerful and complex email receiving protocol. It improves POP3 deficiency. The port number is 143.

SMTP can only be transmitted based on text. It cannot directly transmit images, videos, and other non-text information. However, it can be encoded in binary format and transmitted through SMTP in combination with an auxiliary protocol called MIME.

Email message format:

      What is CC?

Suppose A sends an email to B and CC it to C, then B can see, "Oh, A sent an email to me, but it also sent to C, this email was watched by C ".

      What is spam?

Similarly, if A sends an email to B and secretly sends it to C, B cannot see the email and sends it to C. "Oh, A only sends an email to me ".

SMTP protocol: role:

After a connection is established between the sender's computer and the mail server that supports SMTP, the email is sent to the mail server of the recipient accurately. If the email is sent across multiple networks, SMTP can be transmitted over a network.

Three phases of SMTP transmission:

Note: The following does not refer to establishing a TCP connection. The three phases are based on the established TCP connection.

Establish a connection: After the TCP25 port connection is established, the sender calls the SMTP client to send the HELO command and its own domain name to indicate the identity to the recipient. If the identity is verified, the recipient will return a response message of "250 OK", and a session connection is established.

    Email transmission: At this stage, the sender uses multiple commands. For example, mail from is used TO indicate the sender's email address and rcpt to indicate the recipient's email address. This command can be sent multiple times, if the server is ready to accept the email, it will reply "250 OK". At this time, the sender can use the DATA command to send the email content. After sending, the server still returns "250 OK", indicating that everything went well.

    Connection release: When no email is transmitted, the sender sends a QUIT command to request to close the connection. Normally, the server returns a 221 response, indicating that the request is closed and the connection is released.

 

POP3 protocol: role:

Similar to SMTP, when the recipient's computer establishes a connection with the mail server that supports POP3 protocol, the emails stored on the server are accurately downloaded to the recipient's host. POP3 is the third version of the POP protocol. It solves the problem that a user on the POP server can delete an email after reading an email.

Three phases of POP3 transmission:

    Establish a connection: After establishing a connection to the TCP110 port, enter the authentication stage. The recipient uses USER and PASS as the USER name and password to provide the server with the authentication.

   Receive email: After the authentication is passed, the transaction processing phase is entered. The recipient can send the POP3 command for corresponding operations. The mail server will accept the command and respond.

   Connection release: The operation is complete. The recipient sends the QUIT command to go to the update status. The server confirms to close the connection and updates the mail storage area.

Finally, I will briefly introduce the IMAP and MIME protocols:

IMAP provides more comprehensive functions, allowing users to freely organize their mailboxes as they manage local files, and provides the mail digest function so that users can download emails selectively, the mailbox sharing function is also provided.

IMAP4 works in three modes: offline, online, and disconnected.

MIME is a mail extension protocol. It encodes binary files to implement the function of transmitting arbitrary data in normal text format.

 

 

Send an email to JavaMail

After the gorgeous split line, I finally came to the part I really wanted to write. When I was studying JavaEE, I had access to the javaMail mail sending function. At that time, I had a very simple understanding of the Email protocol, after reading the email protocol of the computer network, I went back to review the related content of JavaMail. Here is a summary:

Jar package to be imported using javaMail: 1. mail. jar 2. activation. jar javaMail core class: Session:

This session is not another session. Here is a class in javaMail. The Session class defines the basic mail Session. If you get the session, it indicates that you have connected to the mail server, after completing the first step, the Connection is established, and its function is similar to that of JDBC Connection.

How can we get the Session?

By checking the j2ee document, we can find two methods: 1. session. getInstance (Properties prop); 2. session. getInstance (Properties prop, Authenticator auth);, this method returns a Session, but requires two parameters. First, let's look at the first parameter Properties prop. This parameter needs to specify two key-value pairs, the first is to specify the server host name, and the second is to specify whether authentication is required. You can obtain the following information:

Properties prop = new Properties ();
Prop. setProperty ("mail. host", "smtp.qq.com"); // set the server host name
Prop. setProperty ("mail. smtp. auth", "true"); // sets the authentication required

The second parameter, Authenticator, is an interface that indicates the Authenticator, that is, verifying the identity of the client. We need to implement this interface by ourselves. To implement this interface, we need to use the account and password.

MimeMessage:

Is the implementation class of the abstract class Message, indicating a mail object. You can call its set * () method to set the sender, recipient, subject, body, and so on...

InternetAddress:

Is the abstract class Address implementation class, is a mail Address class, used to set the mail sending address, receiving Address, and so on. Such as Address address = new InternetAddress ("839564994@qq.com ");

Transport:

This class implements the Message sending protocol, that is, SMTP. When sending a Message, an abstract method of this class is used to send (Message msg); there are various methods. Of course, the Session can also obtain the Transport instance corresponding to the Protocol. Connect to the email server by passing parameters such as the user name, password, and email server host name, send the message using sendMessage (), and close the connection.

Code implementation:

The following code implements the mail sending process:

/*** Method 1 * use Session. getInstance (Properties prop); * @ throws Exception */@ Test public void sendMail1 () throws Exception {Properties prop = new Properties (); // specify the default mail server host name prop. setProperty ("mail. host "," smtp.163.com "); // set the smtp server to verify prop. setProperty ("mail. smtp. auth "," true "); // specify a Default Message Access Protocol. Session getTransport () returns the Transport object prop. setProperty ("mail. transport. protocol "," smtp "); // 1. Get Connected Session session = Session. getInstance (prop); // 2. get the Transport object through Session, Transport ts = session. getTransport (); // if you do not set the third key-value pair of the preceding prop, you can use the following method: // Transport ts = session. getTransport ("smtp"); // 3. log on to the email server and use your username and password ts. connect ("smtp.163.com", "email user name", "password"); // 4. create Message MimeMessage msg = new MimeMessage (session); // set the sender's email msg. setFrom (new InternetAddress ("15764233178@163.com"); // specifies the recipient's mailbox msg. s EtRecipient (RecipientType. TO, new InternetAddress ("839564994@qq.com"); // specifies the Message Title msg. setSubject ("the first simple email"); // the text of the message msg. setContent ("Hello! "," Text/html; charset = UTF-8 "); // send ts. sendMessage (msg, msg. getAllRecipients (); // closes the connection to ts. close ();}/*** Second Method * use Session. getInstance (Properties prop, Authenticator auth); */@ Test public void sendMail2 () throws Exception {/*** 1. the obtained session * // Properties is the property object of the Session, which is used to encapsulate some common Properties for SMTP. Properties props = new Properties (); // set the smtp server address props. setProperty ("mail. host "," smtp.163.com "); // sets whether user authentication is required for the SMTP server. The default value is false and the value is true. setProperty ("mail. smtp. auth "," true "); Authenticator auth = new Authenticator () {@ Override protected PasswordAuthentication getPasswordAuthentication () {// Note: The following logon username is @ frontend content, if your account is a haha@163.com, just enter haha return new PasswordAuthentication ("Mailbox username", "password") ;}}; Session session = Session. getInstance (props, auth);/*** 2. create MimeMessage */MimeMessage msg = new MimeMessage (session); // set the sender msg. setFrom (new InternetAddress ("15764233178@163.com"); // sets the recipient msg. setRecipients (RecipientType. TO, "839564994@qq.com"); // set to cc msg. setRecipients (RecipientType. CC, "2296634789@qq.com"); // sets the topic msg. setSubject ("the second simple email"); // sets the content msg. setContent ("I am an email", "text/html; charset = UTF-8");/*** 3. send */Transport. send (msg );}

Only text can be sent. If you want to send images, videos, and other multimedia content, you must consider using attachments.

When an email containing attachments is sent, the email body is in the form of multiple parts. when sending text, the setContent () method directly sets the body content. when sending an email with an attachment, you must set the body content to MimeMultiPart.

MimeMultiPart is a collection class of components. What is a component? The relationship between them is as follows:

    

 

The specific code for sending attachments is also very simple. Here we take the attachment as an example, you just need to put the above Code in:

// Set content msg. setContent ("I am an email", "text/html; charset = UTF-8 ");

You can modify it as follows:

MimeMultipart list = new MimeMultipart (); // create the first MimebodtPart, which is the body MimeBodyPart part1 = new MimeBodyPart (); part1.setContent ("this is a spam email containing attachments ", "text/html; charset = UTF-8"); list. addBodyPart (part1); // create the second MimebodtPart, which is the attachment MimeBodyPart part2 = new MimeBodyPart (); // set the attachment content part2.attachFile (new File ("e: /Photo/me.jpg "); // set the displayed file name to solve the garbled problem part2.setFileName (MimeUtility. encodeText (", no error. jpg"); list. addBodyPart (part2); msg. setContent (list );

JavaMail related knowledge, this blog, also speak in detail, you can refer to: http://www.cnblogs.com/xdp-gacl/p/4216311.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.