java mail郵箱驗證
常見的比如新增賬號的時候需要郵箱來激活賬号然後才能正常登陸。
1,整體思路
整體可分為兩部分功能,一是給注冊的郵箱發送一封激活郵件,二是激活郵件中有一連結用來激活賬号。
發送郵件的功能比較簡單,主要是對郵件進行配置,包括連接配接時的協定,權限驗證,建立會話,郵件主題和内容,發送方和接收方等資訊,最後發送即可。
主要涉及的類有:
Properties:設定協定,權限等;
Session:用來建立會話,也就是程式到郵件伺服器的第一次對話;
Message:設定郵件内容,發送方和接收方等。
激活賬号的時候一般都會有一個激活碼,這個激活碼就是使用者建立賬号的時候給使用者設定的一個屬性值,當使用者激活的時候我們再根據這個屬性值去查詢使用者,同時把使用者的另一個屬性值比如”status”從”0”更新為”1”,然後在使用者登入的時候不僅要驗證使用者名和密碼,還要驗證這個”status”的值是不是為”1”,這樣才能正常登入。
2,mail功能編寫
需要的jar包:mail.jar
public class MailUtils {
//String email:使用者用來激活的郵箱
//String emailMsg:郵件内容
public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException, GeneralSecurityException, UnsupportedEncodingException{
// 1.建立一個程式與郵件伺服器會話對象 Session
Properties props = new Properties();
//設定連接配接時的協定為"SMTP"
props.setProperty("mail.transport.protocol", "SMTP");
//主機,qq郵箱就是"smtp.qq.com",163郵箱就是"smtp.163.com"
props.setProperty("mail.host", "smtp.qq.com");
//開啟權限驗證
props.setProperty("mail.smtp.auth", "true");
//ssl加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.setProperty("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
// 建立驗證器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "郵箱授權碼");
}
};
//建立程式到郵件伺服器的第一次對話
Session session = Session.getInstance(props, auth);
//控制台輸出debug資訊
session.setDebug(true);
// 2.建立一個Message,它相當于郵件内容
//相當于擷取信封
Message message = new MimeMessage(session);
//設定發送人
message.setFrom(new InternetAddress("[email protected]"));
//設定發送方式與接收者
message.setRecipient(RecipientType.TO, new InternetAddress(email));
//郵件主題
message.setSubject("activateMail");
//郵件内容
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.建立 Transport用來發送郵件
Transport.send(message);
}
}
3,jsp編寫
<form action="${pageContext.request.contextPath}/regist" method="post">
<input type="hidden" name="method" value="regist"/>
<table align="center" width="30%">
...
<tr>
<td>郵箱</td>
<td><input id="email_id" type="text" name="email"/> </td>
</tr>
<tr>
<td align="center" >
<button id="regist_id" type="submit">注冊</button> </td>
<td><button id="cancle_id" type="button">取消</button> </td>
</tr>
</table>
</form>
”form”表單中有個一隐藏的”input”,我們可以根據隐藏域中的”name”屬性去擷取”value”,然後在背景判斷這個”value”,去做對應的操作,其實就是對請求進行統一管理。
4,servlet編寫
”servlet”中首先對請求類型進行判斷,上邊的隐藏域這時候就用到了,這裡主要模拟一個激活碼,實際當中這個激活碼是在使用者新增賬號的時候生成的,比如用”UUID”随機生成一串字元作為激活碼。
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
request.setCharacterEncoding("utf-8");
String method = request.getParameter("method");
if("regist".equals(method)) {
//注冊操作
regist(request, response);
}else if("active".equals(method)) {
//激活操作
active(request, response);
}
}
public void regist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//這裡是使用者注冊之後顯示的頁面
request.getRequestDispatcher("registLater.jsp").forward(request, response);
//擷取使用者輸入的email
String email = request.getParameter("email");
//模拟一個激活碼"1234"
String activeCode = "1234";
//設定郵件内容,注意連結中的"method"
String emailMsg = "注冊成功,請點選<a href='http://localhost:8080/emailActivate/regist?method=active&activeCode="
+activeCode
+"'>激活</a>,驗證碼是"
+activeCode;
System.out.println("正在發送郵件...");
try {
//發送郵件
MailUtils.sendMail(email, emailMsg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
System.out.println("發送郵件成功");
}
public void active(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//從激活請求連結中擷取"activeCode"
String activeCode = request.getParameter("activeCode");
if("1234".equals(activeCode)) {
System.out.println("激活成功");
//進入到激活成功的頁面
request.getRequestDispatcher("activeSuccess.jsp").forward(request, response);
}
}
5,常見問題
5.1
5.1.1,問題描述
530 Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28 javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl).More information at http://service.mail.qq.com/cgi-bin/help?id=28
5.1.2,問題原因:
沒有ssl加密
5.1.3,解決辦法:
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.setProperty("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
5.2
5.2.1,問題描述
535 Error: 請使用授權碼登入。詳情請看: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
javax.mail.AuthenticationFailedException: 535 Error: ?????????¨?????????ê?é????: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
5.2.2,問題原因:
這個就很明顯了,需要使用授權碼登入(此處用的是QQ郵箱發送檔案)
5.2.3,解決辦法:
進入QQ郵箱首頁,點選設定->賬戶
然後往下翻頁,
把第一個“開啟”,按照提示操作,最後會生成一個授權碼,寫入PasswordAuthentication(“郵箱賬号”, “授權碼”)就OK了,如果還有問題,把圖中的第二個也開啟,兩個授權碼不一樣,但是都可以用。