Javaweb in the use of javamail implementation of the message to send a detailed example _java

Source: Internet
Author: User
Tags thread class

Now a lot of websites are provided with the user registration function, usually after we register successfully, we will receive a mail from the registered website. The contents of the message may contain information such as our registered username and password and a hyperlink to activate the account. Today we have to implement a function, the user registration after the success of the user's registration information in the form of email sent to the user's registered mailbox, to achieve the function of sending mail will have to rely on javamail.

First, build the development environment

1.1. Create a Web project

  

1.2, the user registers the JSP page

register.jsp

<%@ page language= "java" pageencoding= "utf-"%>
<! DOCTYPE html>
 
 

1.3. Message Prompt page

message.jsp

<%@ page language= "java" pageencoding= "utf-"%>
<! DOCTYPE html>
 
 

Second, the preparation processing user registers the processing procedure

2.1, the development of Packaging user registration information domain

User.java

Package me.gacl.domain;
public class User {
private String username;
private String password;
private String Email;
Public String GetUserName () {return
username;
}
public void Setusername (String username) {
this.username = username;
}
Public String GetPassword () {return
password;
}
public void SetPassword (String password) {
this.password = password;
}
Public String Getemail () {return
email;
}
public void Setemail (String email) {
This.email = email;
}
}

2.2, write the message to send the function

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

Package Me.gacl.web.controller;
Import java.util.Properties;
Import Javax.mail.Message;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
Import Me.gacl.domain.User; /** * @ClassName: Sendmail * @Description: Sendmail class Inherits thread, so Sendmail is a thread class that is used to send an email to a specified user * @author: Lonely Wolf * @da TE:-PM:: * */public class Sendmail extends Thread {//The mailbox that is used to send a message to the user is private String from = "gacl@sohu.com";//Mailbox Username PR
Ivate String username = "GaCl";
Password of the mailbox private String password = "Mailbox Password";
The server address for sending the message is private String host = "smtp.sohu.com";
private user user; 
Public Sendmail (user user) {this.user = user}/* Overrides the implementation of the Run method to send a message to the specified user * @see Java.lang.thread#run () in the Run method @Override public void Run () {try{Properties prop = new properties (); Prop.setproperty ("Mail.host", host); Prop.setproperty ("Mail.
Transport.protocol "," SMTP ");
Prop.setproperty ("Mail.smtp.auth", "true"); Session session = Session.getinstance(prop);
Session.setdebug (TRUE);
Transport ts = Session.gettransport ();
Ts.connect (host, username, password);
Message message = Createemail (Session,user);
Ts.sendmessage (Message, message.getallrecipients ());
Ts.close ();
}catch (Exception e) {throw new RuntimeException (e);}} /** * @Method: Createemail * @Description: Create a message to send * @Anthor: Aloof Wolf * @param session * @param user * @return * @throws Ex Ception */Public message Createemail (session Session,user User) throws exception{mimemessage message = new MimeMessage (
session);
Message.setfrom (New InternetAddress (from));
Message.setrecipient (Message.RecipientType.TO, New InternetAddress (User.getemail ()));
Message.setsubject ("User registered mail");
String info = "Congratulations on your registration success, your username:" + user.getusername () + ", your password:" + user.getpassword () + ", please safekeeping, if you have questions, please contact the website customer service!!";
Message.setcontent (Info, "text/html;charset=utf-");
Message.savechanges ();
return message; }
}

2.3, writing a servlet to process user Registration

Package Me.gacl.web.controller;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Me.gacl.domain.User;
Import Me.gacl.service.UserService; public class Registerservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp
Onse) throws Servletexception, IOException {try{String username = request.getparameter ("username");
String Password = request.getparameter ("password");
String email = request.getparameter ("email");
User user = new user ();
User.setemail (email);
User.setpassword (password);
User.setusername (username);
SYSTEM.OUT.PRINTLN ("Register user information in the database");
It is time-consuming to send an email//email to a user after the user registers successfully, so there is another thread dedicated to sending mail Sendmail send = new Sendmail (user);
Start the thread, and after the thread starts, the Run method is executed to send the message Send.start ();
Registered user//new UserService (). RegisterUser (user); Request.setattribute ("message", "Congratulations, registered successfully, we have sent aSealed with the registration information email, 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 (); Request.setattribute ("Message", "Registration failed!!")
");
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {do
Get (request, response); }
}

The effect of program operation is as follows:

  

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

When the summary uses JavaMail to send the mail to discover, sends the mail to the Sina or Sohu's mailbox, does not have to be able to receive the mail immediately, always has the delay, sometimes even can defer for a long time, even can be treated as the spam to dispose of, or simply refuses to receive, Sometimes in order to see the effect of the mail to send success, to wait half a day, it is helpless ah.

The above is a small series to introduce the Java mail function of the example code, I hope to help you!

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.