Use JavaMail to send mail in Web Apps

Source: Internet
Author: User

Many websites now offer a user registration function, and usually we receive a mail from the registered website after we have successfully registered. The contents of the message may contain information such as our registered user name and password and a hyperlink to the active account. Today we also come to realize a function like this, after the user registration is successful, the user's registration information in the form of e-mail sent to the user's registered mailbox, the implementation of the message can be sent through the use of javamail.

I. Build a development environment 1.1. Create a Web project

  

1.2. User-registered JSP page

register.jsp

1 <%@ page language= "java" pageencoding= "UTF-8"%> 2 <! DOCTYPE html> 3 
1.3. Message Prompt page

message.jsp

1 <%@ page language= "java" pageencoding= "UTF-8"%> 2 <! DOCTYPE html> 3 
Second, write processing User registration processing program 2.1, the development of Packaging user registration information domain

User.java

1 package me.gacl.domain; 2  3 public class User {4     private string username; 5     private string password; 6     private string email; 7
   public string GetUserName () {8         return username; 9     }10 public     void Setusername (String username) {         One This.username = username;12     }13 public     String GetPassword () {+         return password;15     }16 public void SetPassword (string password) {         This.password = password;18     }19 public     String Getemail () {         return email;21     }22 public     void Setemail (String email) {         This.email = email;24     }25}
2.2, write the Mail send function

Sending a message is a very time-consuming task, so design a thread class to send mail

 1 package Me.gacl.web.controller; 2 3 Import java.util.Properties; 4 Import Javax.mail.Message; 5 Import javax.mail.Session; 6 Import Javax.mail.Transport; 7 Import javax.mail.internet.InternetAddress; 8 Import Javax.mail.internet.MimeMessage; 9 Import me.gacl.domain.user;10/**12 * @ClassName: Sendmail13 * @Description: SendMail class Inherits thread, so SendMail is a thread class, This thread class is used to send Email14 * @author to the specified user: Aloof Wolf * @date: 2015-1-12 PM 10:43:4816 *17 * * public class Sendmail extends Thread {1 9//mailbox used to send mail to the user the private string from = "[email protected]"; 21//The user name of the mailbox  Rname = "GaCl"; 23//The password for the mailbox is the private string password = "Mailbox password"; 25//The server address of the sending message is the private string host = "smtp.sohu.com"; user user;29 public Sendmail (user user) {This.user = user;31}3 2 33/* Override the Run method's implementation to send a message to the specified user in the Run method * @see Java.lang.thread#run () */36 @Override37 Public V OID Run () {try{Prop Properties = new properties (); Prop.setproperty ("Mail.host", host); PROP.S Etproperty ("Mail.transport.protocol", "SMTP"), Prop.setproperty ("Mail.smtp.auth", "true"), Ses sion session = Session.getinstance (prop), Session.setdebug (true), Transport ts = session.gettr Ansport (); Ts.connect (host, username, password); Message message = Createemail (Session,user); 4 8 ts.sendmessage (Message, message.getallrecipients ()); Ts.close ();}catch (Exception E  {runtimeexception (e);}53}54/**56 * @Method: createEmail57 * @Description: Create a message to send * @Anthor: Aloof Wolf *60 * @param session61 * @param user62 * @return63 * @t         Hrows Exception64 */67 public Message Createemail (Session session,user User) throws exception{66 MimeMessage message = New MimeMessage (session), Message.setfrom (new InternetAddress (from)), Message.setrecipient (message.re  Cipienttype.to, New InternetAddress (User.getemail ())); Message.setsubject ("User registration Mail"); info = "Congratulations on your registration success, your user name:" + user.getusername () + ", your password:" + user.getpassword () + ", please keep it properly, if there is a problem, please contact website customer service!"; Message.setcontent (Info, "Text/html;charset=utf-8"); Message.savechanges (); 76}77}
2.3. Write a servlet that handles user registration
 1 package Me.gacl.web.controller; 2 3 Import java.io.IOException; 4 Import javax.servlet.ServletException; 5 Import Javax.servlet.http.HttpServlet; 6 Import Javax.servlet.http.HttpServletRequest; 7 Import Javax.servlet.http.HttpServletResponse; 8 Import Me.gacl.domain.User; 9 Import me.gacl.service.userservice;10 One public class Registerservlet extends HttpServlet {All public void doget (H Ttpservletrequest request, HttpServletResponse response) throws Servletexception, IOException { Y{16 string username = Request.getparameter ("username"), and the string password = Request.getparameter (             "Password"); String email = request.getparameter ("email"); User user = new user (); 20             User.setemail (email), User.setpassword (password); User.setusername (username); 23            SYSTEM.OUT.PRINTLN ("Register user information in the database"); 25//user registration after the successful use of the user registration of the mailbox to send a message to the user Email26 Sending a message is a very time-consuming thing, so there is another thread dedicated to sending mail Sendmail send = new Sendmail (user), 28//Start thread, run after thread starts method to send mail Send.start (); 30 31//Registered users//new userservice (). RegisterUser (use R); Request.setattribute ("message", "Congratulations, the registration is successful, we have sent a letter with the registration information, please check, if not received, may be the network reasons, after a while to receive!! "); Request.getrequestdispatcher ("/message.jsp "). Forward (request, response);}catch (Exception e) {e.printstacktrace (); PNs Request.setattribute ("message", "Registration failed!! "); Request.getrequestdispatcher ("/message.jsp "). Forward (request, response);}40}41-Pu Blic void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept Ion {doget (request, response); 45}46}

The program works as follows:

  

Now many sites have such a function, after the user registration is completed, the site according to our registration filled out the email to us an email, and then click on the hyperlink in the email to activate our users. This is how this function is implemented.

In summing up the use of javamail send mail, found that the mail sent to Sina or Sohu mailbox, not necessarily be able to receive the mail immediately, there is always a delay, and sometimes even delay a long time, or even be treated as spam, or simply refuse to receive, Sometimes in order to see the effect of e-mail delivery success, to wait half a day, it is helpless ah.

Use JavaMail to send mail in Web Apps

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.