首先需要javax.mail的mail-1.4.7.jar
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
註冊的業務
public void processRegister(User model) {
/// 如果處於安全,可以將激活碼處理的更復雜點
// user.setValidateCode(MD5Tool.MD5Encrypt(email));
model.setValidateCode(MD5Util.encode2hex(model.getEmail()));
// 保存註冊信息
userMapper.insert(model);
/// 郵件的內容
StringBuffer sb = new StringBuffer("點擊下面鏈接激活賬號,鏈接只能使用一次,請儘快激活!<br/>");
sb.append("http://localhost:8080/registerValidate?email=");
sb.append(model.getEmail());
sb.append("&validateCode=");
sb.append(model.getValidateCode());
// 發送郵件
SendEmail.send(model.getEmail(), sb.toString());
}
傳入的model是經過前臺驗證的實體
MD5Util類
public class MD5Util {
/**
* 將源字符串使用MD5加密爲字節數組
*/
public static byte[] encode2bytes(String source) {
byte[] result = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(source.getBytes("UTF-8"));
result = md.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 將源字符串使用MD5加密爲32位16進制數
*/
public static String encode2hex(String source) {
byte[] data = encode2bytes(source);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < data.length; i++) {
String hex = Integer.toHexString(0xff & data[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
/**
* 驗證字符串是否匹配
*
* @param unknown
* 待驗證的字符串
* @param okHex
* 使用MD5加密過的16進制字符串
* @return 匹配返回true,不匹配返回false
*/
public static boolean validate(String unknown, String okHex) {
return okHex.equals(encode2hex(unknown));
}
}
SendEmail類
public class SendEmail {
public static final String HOST = "smtp.163.com";
public static final String PROTOCOL = "smtp";
public static final int PORT = 25;
public static final String FROM = "[email protected]";// 發件人的email
public static final String PWD = "xxxxxxxx";// 發件人密碼
/**
* 獲取Session
*/
private static Session getSession() {
Properties props = new Properties();
props.put("mail.smtp.host", HOST);// 設置服務器地址
props.put("mail.store.protocol", PROTOCOL);// 設置協議
props.put("mail.smtp.port", PORT);// 設置端口
props.put("mail.smtp.auth", true);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM, PWD);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
return session;
}
public static void send(String toEmail, String content) {
Session session = getSession();
try {
// Instantiate a message
Message msg = new MimeMessage(session);
// Set message attributes
msg.setFrom(new InternetAddress(FROM));
InternetAddress[] address = { new InternetAddress(toEmail) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("賬號激活郵件");
msg.setSentDate(new Date());
msg.setContent(content, "text/html;charset=utf-8");
// Send the message
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
以163郵箱爲例
ServiceException類
public class ServiceException extends Exception {
private static final long serialVersionUID = -1708015121235851228L;
public ServiceException(String message) {
super(message);
}
}