Servlet & JSP (26)

Source: Internet
Author: User
Tags email string

This article introduces JSP and javamail. As more and more Java Web applications need to integrate the email function, the javamail component perfectly solves this problem.

How email works

The email process follows the customer-server mode. Each email is sent to both the sender and receiver. The sender acts as the client, and the receiver acts as the server. The server contains email addresses of many users. The sender sends the edited email to the SMTP server through the email client program. The SMTP server identifies the recipient's address and sends messages to the POP3 server that manages the address. The email server stores messages in the recipient's email address and notifies the recipient of new emails. After logging on to the client, the recipient will see the prompt.

Protocols

SMTP protocol (Simple Mail Transfer Protocol, Simple Mail Transfer Protocol) is used to ensure reliable and efficient email delivery. It uses port 25 for transmission. When the sender and receiver are in the same network, it will directly send the email to the receiver. Otherwise, one or more intermediate servers are required for forwarding. Therefore, its receiver can be used as the final or mail server.

The POP3 protocol (Post Office Protocol) is used to receive emails. The third frequently used version is POP3. It uses the port 110. Through the POP protocol, you can delete or download your emails to your local computer after logging on to the server. It is an offline protocol standard.

Javamail Introduction

Javamail is an API released by Sun to process emails. It supports various email communication protocols. To use javamail in a Java Web program, copy the mail. jar and activation. jar of javamail to the WEB-INF/lib directory. You can call javamail APIs to conveniently operate emails in your applications.

The core classes of javamail mainly include Session, message, address, authenticator, transport, store, and folder.

Session

Like HTTP sessions, the session class defines basic mail sessions. The session uses the java. util. propertities object to obtain the shared information used by the email server, user name, password, and the entire application.

Message class

The message object is used to store the actually sent email information. The message object is created as a mimemessage object. during creation, a session object must be specified as a parameter. After creating the message object, you can set some information for it. When you add content to a message object, you can use the settext () method to set the content if it contains HTML or attachments, you can set it using the setcontent () method.

Address class

After a session and message are created, the address Class address must be used to indicate the address for the email. Like the message class, the address class is an abstract class, And javax. Mail. Internet. internetaddress is a subclass of address. You can use it to create an address object.

Authenticator class

The javamail API accesses the mail server by using an authorization class (authenticator) as the user name and password. When using the authenticator class, you must inherit the abstract class, And the inherited class must have the getpasswordauthencation () method that returns the passwordauthentication object.

Transport class

The transport class uses the specified account and password to connect to the specified email sending server to send emails Based on the specified mail sending protocol.

Store class

Store indicates the mail server that stores emails. You can obtain a specific type of store from the session, and connect to the store according to the specified account, password, and authorization. The store class implements reading, writing, monitoring, and searching operations on specific mail protocols. You can use the javax. Mail. Store class to access the javax. Mail. folde class.

Folder class

The folder class represents the folder through which you can access the emails in the folder. You can use the getfolder () method of the store object to obtain a folder object.

For example, an application code for sending an email with attachments is as follows:

Package test; import javax. mail. *; import javax. mail. internet. *; import javax. activation. *; import Java. util. *; public class sendattachmail {string smtphost = ""; // SMTP Server String user = ""; // log on to the SMTP server account string Password = ""; // The password for logging on to the SMTP Server String from = ""; // sender's email string to = ""; // recipient's email string subject = ""; // mail title string content = ""; // mail content string filename = ""; // attachment file name // No parameter constructor public sendattachmail () {} Public String getcontent () {return content;} public void setcontent (string content) {try {// solve the Chinese content problem content = new string (content. getbytes ("ISO8859-1"), "gb2312");} catch (exception ex) {ex. printstacktrace ();} This. content = content;} Public String getfilename () {return filename;} public void setfilename (string filename) {try {// solve the Chinese problem of file name filename = new string (filename. getbytes ("ISO8859-1"), "gb2312");} catch (exception ex) {ex. printstacktrace ();} // replace '\' in the file path with '/' filename = filename. replaceall ("\\\\", "/"); this. filename = filename;} Public String getfrom () {return from;} public void setfrom (string from) {This. from = from;} Public String GetPassword () {return password;} public void setpassword (string password) {This. password = password;} Public String getsmtphost () {return smtphost;} public void setsmtphost (string host) {smtphost = host;} Public String getsubject () {return subject ;} public void setsubject (string subject) {try {// solve the title's Chinese question subject = new string (subject. getbytes ("ISO8859-1"), "gb2312");} catch (exception ex) {ex. printstacktrace ();} This. subject = subject;} Public String getto () {return to;} public void setto (string to) {This. to = to;} Public String getuser () {return user;} public void setuser (string user) {This. user = user;} // send the public Boolean send () {// create an attribute object properties props = new properties (); // specify the SMTP server props. put ("mail. SMTP. host ", smtphost); // specifies whether SMTP authentication props is required. put ("mail. SMTP. auth "," true "); try {// create an authorization verification object smtpauth auth = new smtpauth (); Auth. setaccount (user, password); // create a session object session mailsession = session. getinstance (props, auth); mailsession. setdebug (true); // create a mimemessage object mimemessage message = new mimemessage (mailsession); // specify the sender's email message. setfrom (New internetaddress (from); // specifies the recipient's email message. addrecipient (message. recipienttype. to, new internetaddress (to); // specify the message subject. setsubject (subject); // specifies the mail sending date message. setsentdate (new date (); // specify the mail Priority 1: urgent 3: Normal 5: Slow message. setheader ("X-priority", "1"); message. savechanges (); // create a mimemultipart object to store multiple bodypart objects multipart Container = new mimemultipart (); // create a new bodypart object bodypart textbodypart = new mimebodypart (); // set the content and format of the bodypart object/the encoding method textbodypart. setcontent (content, "text/html; charset = gb2312"); // Add the bodypart containing the letter content to the container in the mimemultipart object. addbodypart (textbodypart); // create a bodypart object bodypart filebodypart = new mimebodypart (); // use the local file as the attachment filedatasource FDS = new filedatasource (filename ); filebodypart. setdatahandler (New datahandler (FDS); // process the Chinese problem of the attachment file name in the email string attachname = FDS. getname (); attachname = new string (attachname. getbytes ("gb2312"), "ISO8859-1"); // sets the attachment file name filebodypart. setfilename (attachname); // Add the attachment's bodypart object to the container. addbodypart (filebodypart); // use container as the message object content. setcontent (container); // create a transport object transport Transport = mailsession. gettransport ("SMTP"); // connect to the SMTP server transport. connect (smtphost, user, password); // send the email transport. send (message, message. getallrecipients (); transport. close (); Return true;} catch (exception ex) {ex. printstacktrace (); Return false ;}// defines an SMTP authorization verification class static class smtpauth extends authenticator {string user, password; // sets the account information void setaccount (string user, string password) {This. user = user; this. password = password;} // obtain the passwordauthentication object protected passwordauthentication getpasswordauthentication () {return New passwordauthentication (user, password );}}}

Reprinted please indicate the source: http://blog.csdn.net/iAm333

Related Article

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.