在较小的项目中,如果只需要实现发送邮箱验证码的基本功能,不想搭建邮箱服务器,则可以简单地使用SMTP实现验证码的发送功能,可以简单的写一个工具类
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;
public class SMTPUtil {
//smtp邮箱名称
private static final String HOST = "smtp.qq.com";
//发送邮箱地址
private static final String senderEmail = "xxxxx@qq.com";
//邮箱的smtp密码
private static final String senderPassword = "xxxxxx";
//邮件标题
private static final String subject = "验证码测试";
//验证码的长度
private static final int codeLength = 6;
//验证码中是否含有大写英文字母
private static final boolean hasLetter = true;
//发送验证码
public static void sendVerifyCode(String mailAdr){
String code = getCode(codeLength,hasLetter);
sendMail(mailAdr,subject,code);
}
//利用smtp发送邮件
public static void sendMail(String mailAdr, String subject, String content) {
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", HOST);
props.put("mail.user", senderEmail);
props.put("mail.password", senderPassword);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
Session mailSession = Session.getInstance(props,authenticator);
MimeMessage message = new MimeMessage(mailSession);
try{
InternetAddress from = new InternetAddress(props.getProperty("mail.user"));
message.setFrom(from);
InternetAddress to = new InternetAddress(mailAdr);
message.setRecipient(RecipientType.TO,to);
message.setSubject(subject);
message.setContent(content,"text/html;charset=UTF-8");
Transport.send(message);
}catch (MessagingException e){
e.printStackTrace();
}
}
//生成验证码
public static String getCode(int size,boolean hasLetter) {
String num = "";
Random random = new Random();
//生成字母
if (hasLetter) {
for (int i = 0; i < size; i++) {
//利用奇偶数决定下一个是数字还是字母
int isLetter = random.nextInt(10) % 2;
//偶数生成英文字母
if (isLetter == 0) {
//大写字母的ascii码是65到90
num = num + (char) (random.nextInt(26) + 65);
} else {
//数字的ascii码是48到57
num = num + (char) (random.nextInt(10) + 48);
}
}
}
//不生成字母
else{
for (int i = 0; i < size; i++) {
num = num + (char) (random.nextInt(10) + 48);
}
}
//检查生成的验证码的长度
if (num.length() != size) {
return null;
} else {
return num;
}
}
}