7 May 2019
Java Mail----Sending an Email using Java
by Jerry Zhang
#Tip of the Day:
Send an Email
- Create a connection to mail server
Properties properties = new Properties();
//properties.setProperty("host","localhost");
Authenticator authenticator = new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("service@jmail.com","111");
}
};
Session session = Session.getInstance(properties, authenticator);
- Create an email object
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("service@jmail.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Activate your account by clicking the link.");
message.setContent(
"<h1>Activate your account by clicking the link blow: </h1>" +
"<h3><a href='http://localhost:8080/ActiveServlet?code="+code+"'>" +
"http://localhost:8080/ActiveServlet?code="+code+"</a></h3>",
"text/html; charset=UTF-8");
- Send the activation email
Transport.send(message);
Activate the account
After sending the email, the user can click the link in the email. The new request contains the code we sent as a parameter. We need to create another servlet to handle it. In this servlet:
-
Get the user from the database by the code parameter.
-
If the user is found, change the user activation state to 1, clear the code, and update the user’s information. If the user is not found, tell the user activation failed.
JDBC for Serial type
PreparedStatement statement;
String sql = "UPDATE hmail.userinfo SET username = ?, password = ?, nickname = ?, email = ?, " +
"state = ?, code = ? WHERE uid = ?";
statement = getPreparedStatement(user, connection, sql);
statement.setObject(7, user.getUid());
Note that if we have to set a value for the serial type uerid, we have to use the setObject
method.