Nowadays, many websites provide user registration function. Usually, after we successfully register, we will receive an email from the registered website. The contents of the email may contain information such as our registered username and password, as well as a hyperlink to activate the account. Today we will also implement such a function. After the user registers successfully, the user's registration information will be sent to the user's registration email in the form of an email. To realize the email sending function, JavaMail must be used.
1. Build a development environment
1.1. Create a Web Project
1.2. User registration Jsp page
register.jsp
<%@ page language="java" pageEncoding="UTF-"%><!DOCTYPE HTML><html><head><title>Register Page</title></head><body><form action="${pageContext.request.contextPath}/servlet/RegisterServlet" method="post">Username: <input type="text" name="username"><br/>Password: <input type="password" name="password"><br/>Email: <input type="text" name="email"><br/>Input type="submit" value="Register"></form></body></html>1.3. Message prompt page
message.jsp
<%@ page language="java" pageEncoding="UTF-"%><!DOCTYPE HTML><html><head><title>Message prompt page</title></head><body>${message}</body></html>2. Write a user registration processing program
2.1. Develop a domain that encapsulates user registration information
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 email sending function
Sending emails is a very time-consuming thing, so here is a thread class to send emails
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: The Sendmail class inherits Thread, so Sendmail is a thread class, which is used to send email to the specified user* @author: Guarantor* @date: -- Afternoon::**/ public class Sendmail extends Thread {//The email address used to send emails to users private String from = "[email protected]";//The user name of the email address private String username = "gacl";//The password of the email address private String password = "email password";//The server address of the sender private String host = "smtp.sohu.com";private User user;public Sendmail(User user){this.user = user;}/* Rewrite the implementation of the run method and send emails to the specified user in the run method* @see java.lang.Thread#run()*/@Overridepublic 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);sssion.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 the email to be sent* @Anthor: Lonely Canglang** @param session* @param user* @return* @throws Exception*/ 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 Registration Email");String info = "Congratulations on your successful registration, your username: " + user.getUsername() + ", your password: " + user.getPassword() + ", please keep it properly. If you have any questions, please contact the website customer service!!"; message.setContent(info, "text/html;charset=UTF-");message.saveChanges();return message;}}2.3. Write a Servlet that handles 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 response)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");//After the user registers successfully, send an email to the user using the email address when the user registers.//Send emails is a very time-consuming task, so another thread is opened here to specifically send emails Sendmail send = new Sendmail(user);//Start the thread, and after the thread starts, it will execute the run method to send emails send.start();//Register user//new UserService().registerUser(user);request.setAttribute("message", "Congratulations, the registration was successful. We have sent an email with the registration information. Please check it. If you don't receive it, it may be due to the Internet. You will receive it in a while! ! ");request.getRequestDispatcher("/message.jsp").forward(request, response);}catch (Exception e) {e.printStackTrace();request.setAttribute("message", "Register failed!!");request.getRequestDispatcher("/message.jsp").forward(request, response);}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, Response);}}The program runs as follows:
Many websites now have such functions. After the user registration is completed, the website will send us an email based on the email address we filled in when registering, and then click the hyperlink in the email to activate our users. This is how this function is implemented.
When summarizing the use of JavaMail to send emails, it is found that when sending emails to sina or sohu's mailboxes, you may not be able to receive the emails immediately. There is always a delay, sometimes it will be delayed for a long time, and it will even be processed as spam, or you may simply refuse to receive them. Sometimes, it is helpless to wait for a long time to see the successful email sending effect.
The above is the example code of the java mail sending email function introduced to you by the editor. I hope it will be helpful to everyone!