1. 程式人生 > >java實現qq郵箱傳送註冊驗證碼

java實現qq郵箱傳送註冊驗證碼

import javax.mail.*;
import javax.mail.internet.MimeMessage;
/**
 *
 * @param email  傳送郵箱驗證碼(註冊)
 * @return 驗證碼給前段
 */
@RequestMapping(value = "/verifyEmail",method= RequestMethod.POST)
@ResponseBody
public String verifyEmail(@RequestParam("email") String email){
    Properties prop = new Properties();
    // 開啟debug除錯,以便在控制檯檢視
prop.setProperty("mail.debug", "true"); // 設定郵件伺服器主機名 prop.setProperty("mail.host", "smtp.qq.com"); // 傳送伺服器需要身份驗證 prop.setProperty("mail.smtp.auth", "true"); // 傳送郵件協議名稱 prop.setProperty("mail.transport.protocol", "smtp"); prop.put("mail.smtp.ssl.enable", "true"); // 建立session Session session = Session.getInstance
(prop); // 通過session得到transport物件 Transport ts = null; try { ts = session.getTransport(); } catch (NoSuchProviderException e) { e.printStackTrace(); } // 連線郵件伺服器:郵箱型別,帳號(12345678)換成傳送人的QQ,授權碼:hpifogzyvixdbfbh,這是我的,你要換成你自己的 try { ts.connect("smtp.qq.com", "12345678"
, "hpifogzyvixdbfbh");// 後面的字元是授權碼 } catch (MessagingException e) { e.printStackTrace(); } //隨機生成四位數字 String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuilder stringBuilder=new StringBuilder(4); for(int i=0;i<4;i++) { char ch=str.charAt(new Random().nextInt(str.length())); stringBuilder.append(ch); } MimeMessage message=null; // 建立郵件 try {
     //emailService這個類我就不給出了,你換成自己的servlet層,呼叫就可以了
     message=emailService.createSimpleMail(session,email,stringBuilder.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 傳送郵件
try {
        ts.sendMessage(message, message.getAllRecipients());
        session.setDebug(true);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    try {
        ts.close();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    String cunt=stringBuilder.toString();
    return cunt;
}
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
 * 註冊
 * @Method: createSimpleMail
 * @Description: 建立一封只包含文字的郵件
 */
public  MimeMessage createSimpleMail(Session session, String email,String stringBuilder) throws Exception  {
    // 建立郵件物件
MimeMessage message = new MimeMessage(session);
    // 指明郵件的發件人[email protected]
message.setFrom(new InternetAddress("[email protected]"));
    // 指明郵件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
    // 郵件的標題
message.setSubject("sea View 賬號註冊");
    // 郵件的文字內容
message.setContent("歡迎您註冊sea View,賬號註冊驗證碼為(一分鐘有效):"+stringBuilder+",請勿回覆此郵箱", "text/html;charset=UTF-8");
    // 返回建立好的郵件物件
return message;
}