用java實現郵箱驗證其實很簡單
我們只需要一個jar包
先創建一個郵箱發送類
public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1.創建一個程序與郵件服務器會話對象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.163.com");
props.setProperty("mail.smtp.auth", "true");// 指定驗證爲true
// 創建驗證器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("cui******@163.com", "12313456");//註冊郵箱的帳號和授權碼
}
};
Session session = Session.getInstance(props, auth);
// 2.創建一個Message,它相當於是郵件內容
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("**********@163.com","8896"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 設置發送者
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設置發送方式與接收者
message.setSubject("用戶激活");
// message.setText("這是一封激活郵件,請<a href='#'>點擊</a>");
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.創建 Transport用於將郵件發送
Transport.send(message);
}
}
這裏我用的是網易郵箱,郵箱需要設置開通smtp協議,得到授權碼
測試類
public class Test { public static void main(String[] args) { try {
String emailMsg="這是一封激活郵件"; MailUtils.sendMail(驗證的郵箱, emailMsg); System.out.println("郵件發送成功!"); } catch (MessagingException e) { e.printStackTrace(); } } }