情景:使用java发送邮件验证码
利用java发送邮件需要做一些准备操作:
这里使用到了qq邮箱。
首先,打开qq邮箱,在设置,帐户那里,开启pop3/smtp,和imap/smtp服务。这里开启需要手机发送短信来验证。
而后,点击下方得生成授权码,会要求使用手机来验证。验证ok后,会生成一串授权码,记住它,后面有用。使用java mail来利用qq邮箱发送邮件就需要这个授权码。(这里有个需要注意得点是:这个16位的授权码显示的时候是4个4个一组得显示,但是,实际上,授权码是16位连续的,中间没有空格,这个在后面输入的时候要注意!,要不然会报535错误!)
使用java来使用mail服务,需要相应的包,这个包有3个,在我的上传资源里可以找到。
接下来上代码就完事了:
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
public class JavaMailUtil {
//发件人的邮箱和密码
public static String emailAccount="qq邮箱地址";
//发件人的邮箱得授权码
public static String emailPassword="授权码";
//发件人邮箱得服务地址
public static String emailSMTPHost="smtp.qq.com";
//收件人邮箱
public static String receiveMailAccount="";
/**
* 创建一封邮件对象
* @param session
* @param sendMail
* @param receiveMail
* @param html
* @return
* cc:抄送
* Bcc:密送
* To:发送
*/
public static MimeMessage createMimeMessage(Session session,String sendMail,String receiveMail,String html) throws UnsupportedEncodingException, MessagingException {
//创建一封邮件对象
MimeMessage message = new MimeMessage(session);
//From:发件人
message.setFrom(new InternetAddress(sendMail,"发送方的名字","utf-8"));
//To:收件人(也可以抄送或者密送)
message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(receiveMail,"对方name","utf-8"));
//Subject:邮件的主题
message.setSubject("邮箱验证","utf-8");
//content:邮件正文(可以使用html标签)
message.setContent(html,"text/html;charset=UTF-8");
//设置发送时间
message.setSentDate(new Date());
//保存设置
message.saveChanges();
return message;
}
}
还需要一个类来生成随机数:
import java.lang.ref.SoftReference;
public class RandomUtil {
public static String getRandom(){
String[]letters=new String[]{"q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
"A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
"0","1","2","3","4","5","6","7","8","9"
};
String code="";
for(int i=0;i<6;i++)
{
code=code+letters[(int)Math.floor(Math.random()*letters.length)];
}
return code;
}
}
public class htmlText {
public static String sendHtml(String code)
{
String html="Email地址验证<br/>"+
"这封邮件是快拼网发送的。<br/>"+
"你收到的这封邮件是csdn进行新用户注册的。<br/>"+
"账号激活声明<br/>"+
"请将下面的验证码输入提示框里即可!"+
"<h3 style='color:red;'>"+code+"</h3><br/>";
return html;
}
}
这是邮件的内容。
使用的时候:
@RequestMapping("sendEmail")
@ResponseBody
public String sendEmail(String email, HttpSession httpSession){
JavaMailUtil.receiveMailAccount=email;//给用户输入的邮箱发送邮件
//1.创建参数配置,用来连接邮箱服务器的参数配置
Properties props = new Properties();
//开启Debug模式
props.setProperty("mail.debug","true");
//发送服务器需要身份验证
props.setProperty("'mail.smtp.auth","true");
//设置邮件服务器的主机名
props.setProperty("mail.host",JavaMailUtil.emailSMTPHost);
//发送邮件协议名称
props.setProperty("mail.transport.protocol","smtp");
//2.根据配置创建会话对象用来和邮件服务器交互
Session session = Session.getInstance(props);
//设置debug,可以查看详细的发送log
session.setDebug(true);
//3.创建一封邮件
String code = RandomUtil.getRandom();
System.out.println("邮箱验证码:"+code);
String html = htmlText.sendHtml(code);
MimeMessage message=null;
try {
message= JavaMailUtil.createMimeMessage(session, JavaMailUtil.emailAccount, JavaMailUtil.receiveMailAccount, html);
//4.根据session获取邮件传输对象
Transport transport = session.getTransport();
//5.使用邮箱账号和密码连接邮件服务器emailAccount必须和message中的发件人一样,否则报错
transport.connect(JavaMailUtil.emailAccount,JavaMailUtil.emailPassword);
//6.发送邮件,发送所有收件人的地址
transport.sendMessage(message,message.getAllRecipients());
//7.关闭连接
transport.close();
//写入session
httpSession.setAttribute("code",code);
} catch (Exception e) {
e.printStackTrace();
return "false";
}
return "OK";
}
@RequestMapping("register")
public String register(Register register,HttpSession httpSession){
String code =(String) httpSession.getAttribute("code");
System.out.println(code);
if(code!=null)
{
//获取页面提交的验证码
String inputCode = register.getCode();
System.out.println("页面提交的验证码"+inputCode);
if(code.toLowerCase().equals(inputCode.toLowerCase()))
{
//验证成功,暂时先跳转到这里
return "customer";
}
}
//移除验证码
httpSession.removeAttribute("code");
//验证失败,暂时先跳转到这里
return "login";
}
这样就OK了!