Implement mail delivery in the Web __web

Source: Internet
Author: User
Tags tomcat server

The functionality of the messaging client software can also be integrated into the Web site so that registered users of the Web site can send and receive e-mail via Web pages, such as large portals such as Sina and Sohu, which provide members with the ability to send and receive e-mail via Web pages. For some small and medium sized web sites, while it is not necessary to provide e-mail to the Web page for its members, these sites are likely to need to provide themselves with the ability to send mail to registered users, such as a Web site that automatically sends a welcome email containing its registration information to a newly registered user. For the birthday of the registered members automatically send a congratulatory email, the site's latest activity information sent by email to all registered members. This section mainly explains how to implement mail delivery in small and medium web sites, and the task of delivering mail in a Web site is simple, as long as you rewrite a normal mail-sending program into a Web application. Only mail senders in a Web site typically use their own site's SMTP server to send messages externally, and the process of sending mail to the Web site is shown in the following illustration:

As you can see from the image above, the browser submits the message by accessing the mail-sending program in the Web site, and the mail sender sends the message to the SMTP server of its own web site, and the SMTP server receives the message based on the recipient's address at the destination of the message, Either to a recipient mailbox that is posted to the local domain administration, or to another SMTP server that is transferred to the admin recipient address domain.

Some Web server programs specialize in providing some support for mail-forwarding, for example, Tomcat provides the ability to create javax.mail.session objects by configuration, javax.mail.session classes are used to define the environment required for an entire application, and the first step in writing a javamail program is to create a session object that Tomcat provides a specialized The resource factory for the Javax.mail.Session object created by the door allows the Javax.mail.session object to be configured as a Jndi resource in Tomcat, which creates a session object based on configuration information and registers it with the JNDI environment, when Tomcat starts. In a Web application, you can refer to the session object in a Jndi way, which benefits from setting up the mail server's connection information through a configuration file, and using JavaMail Web applications itself without having to consider the setting of the mail server's information, Instead of simply using Jndi to get pre-configured session objects in Tomcat, if you want to change server information, you just need to modify the Tomcat profile, and you don't need to modify the Web application that uses JavaMail. This also facilitates the use of JavaMail Web applications to migrate between Tomcat servers that have a different messaging service environment.

Here is an example of how messaging functions are implemented on the Web:

1. Configure the JavaMail Jndi environment for Tomcat first:

Can be configured in Context.xml in a tomcat environment so that the configuration is configured for this jndi throughout the Tomcat environment, while the other is configured in the project to set up < within the context.xml of the Web application's Meta-inf directory context> element, choose this way to set the session resource, create a meta-inf directory in the root directory of the Web application, and then create a file in the directory named Context.xml, which reads as follows:

<Context>

<resource

Name= "Mail/session"

Auth= "Container"

Type= "Javax.mail.Session"

Mail.smtp.host= "Smtp.sina.com"

Mail.transport.protocol= "SMTP"

Mail.smtp.auth= "true"

/>

</Context>

After the context.xml file is created within the Web application, the Tomcat server starts the Web application with the <Resource> element to create an Javax.mail.Session instance object and register the session instance object into Tomcat's JNDI environment with the registered name "Mail/session". The instantiation of the session object actually has a tomcat server that invokes a factory class when the Web application starts, and the complete name of the factory class is: Org.apache.naming.factory.MailSessionFactory, Mailsessionfactory is responsible for creating session instance objects based on the configuration information of <Resource> elements.

2.web applications are theoretically not dependent on a specific Web server program, a Web application can be published into a Tomcat server program, and it should be able to be published to other Web server programs such as WebLogic. Because the current Web application references a particular Web server program to create a resource, It is better to declare in the Web.xml file that the resources created by the Web server program referenced by the Web application are declared to indicate that when migrating the current Web application to another Web server program, this resource should also be created on other Web server programs, and for the session resource created above, the Web application Web.xml file, add the following code at the appropriate location:

<web-app>

........

<resource-ref>

<res-ref-name> mail/session </res-ref-name>

<res-type>javax.mail.Session</res-type>

<res-auth>Container</res-auth>

</resource-ref>

</web-app>

The insertion position of the <resource-ref> element can be known based on the DTD or schema of the Web.xml file, especially when the insertion location is wrong, and when Tomcat starts, it prompts for an error message, in fact, in a Tomcat environment, This step of configuring <resource-ref> elements in the Web.xml file can be omitted. The reason for this statement in the Web.xml file is to explicitly tell the Web server program that the Web application needs to refer to the resources on the Web server and that the Web server must create this resource.

3. Install the jar containing the JavaMail API and the jar package containing the JAF API into the <tomcat home directory >/common/lib directory. This is because Tomcat servers need to use the JavaMail API when creating Javax.mail.Session instance objects, and the JavaMail API is needed in Web applications to create message content and send mail, so it needs to be included JavaMail The API and JAF API jar packages are placed in the <tomcat home directory >/common/lib directory, not in the Web-inf/lib directory of the Web application.

Here is an example code:

Package com.codebbs.action;


Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Date;

Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.AddressException;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
Import Javax.naming.Context;
Import Javax.naming.InitialContext;
Import javax.naming.NamingException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

/**
* @author JT
* 2015-11-12 9:34:39
*javaweb Send mail
*/
public class Sendmailservlet extends HttpServlet {


@Override
protected void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
String smtpserver= "smtp.sina.com";//mail Server host name
String protocol= "SMTP";
String username= "Mailbox Account";
String password= "Mailbox Password";
String from= "Sender's mailbox Address";
String to= "recipient mailbox Address";
String subject= "Test";
String body= "Jiang Hang";

Get Session Object
try {
Context Inictx=new InitialContext ();
Context envctx= (Inictx.lookup) ("java:comp/env");
Session session= (session) Envctx.lookup ("Mail/session");

Create a MimeMessage object that represents a message
MimeMessage Msg=new MimeMessage (session);
Msg.setfrom (New InternetAddress (from));
Msg.setrecipient (Message.RecipientType.TO, New internetaddress (to));
Msg.setsentdate (New Date ());
Msg.setsubject (subject);
Msg.settext (body);
Msg.savechanges ();

Transport Transport=session.gettransport ();
Transport.connect (smtpserver, username, password);
Transport.sendmessage (msg, msg.getrecipients (Message.RecipientType.TO));
Transport.close ();

Response.setcontenttype ("TEXT/HTML;CHARSET=UTF-8;");
PrintWriter Out=response.getwriter ();
OUT.PRINTLN ("Your mail has been sent out.") ");


catch (Namingexception e) {
E.printstacktrace ();
catch (Addressexception e) {
E.printstacktrace ();
catch (Messagingexception e) {
E.printstacktrace ();
}
}


@Override
protected void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
This.doget (request, response);
}

}

The JavaMail servlet written above is obviously just a simple example of sending e-mail in a Web application, where information such as the recipient's address, the subject of the message, and the content of the message is simply coded with code, which is obviously of little practical value in practical applications Writing a Web mail send program is not as simple as this Sendmailservlet program, at least to provide a writing page of the content of the message, in this page to fill out the basic information of the message, and then provide this information to the Sendmailservlet program processing, The Sendmailservlet program gets this information and creates a MimeMessage object that represents the content of the message, sends the contents of the message in the MimeMessage object, and provides more functionality in the Web application if you wish:

1. Add additional and inline content to the message. This requires you to select multiple files as attachments to the message and multiple picture files as inline images, which must be uploaded to the Web server before the Web application can insert their contents into the entire MIME mail message, which involves programmatic processing of the file's upload.

2. When referencing embedded images in the body of an HTML message, consider the problem of referencing a path, in which the user writes the label, can not be very good to determine the SRC attribute value, this must be solved by programming design, preferably in the picture insert operation, upload picture file automatically fill in the <src= "..." > tag content, which involves more programming tips and more details about generating MIME messages.

3. Before you send a message, you should also have the ability to preview the message, which involves the resolution and display of the message.

4. Can bulk designated recipient address for mass mailing, the sender address can be specified by some query conditions from the database, can also import from the text file, how to achieve bulk delivery. is to specify more than one recipient to send a message, or to send a separate message to each recipient, or to group the recipients one at a time, and set the size of the group to be more appropriate. These are strategic issues that need to be carefully considered.

5. The size of the content of the message limit, to send the message failed to log records, such as small functions.

Thinking and Practice:

Send the same message to multiple recipients at the same time, when you call the Transport.sendmessage method, assign it multiple recipient addresses, and then view the debugging information that the JavaMail API prints out in this case to understand JavaMail The API is how to implement the underlying details that send the same message to multiple recipients. Add some program code between the statement calling the Transport.sendmessage method and the statement that calls the Transport.claose method, which modifies the contents of the mail message, and then calls the Transport.sendmessage method again to send the modified message to view JAV The Amail API prints the mode information in this case to see how the JavaMail API implements the low-level implementation details of sending multiple messages to the SMTP server on the same TCP connection.

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.