我們在網上註冊賬號的時候通常會給註冊的郵箱發送一個連接來進行用戶的激活操作,在郵箱驗證的過程中,服務端要有自己的郵箱服務器,給註冊的郵箱發送郵件。
郵件協議:常用的 1.smtp 發送郵件協議; 2.pop 接受郵件協議。
郵箱服務的執行過程:
建立自己的郵箱驗證服務
1、搭建郵箱服務器:
安裝 eyoumailserversetup.exe
修改域名: 工具——>服務器設置——>liang.com
註冊賬號:賬號——>新建賬號
安裝客戶端:Foxmail,將服務器改爲本地。
2、myeclipse開發環境設置
在javaee.jar中刪除自帶的發送郵件的jar包,添加自己的jar包到lib目錄下。
3、創建發送郵件類
MailUitls
<span style="font-family:SimSun;font-size:18px;">package cn.itcast.shop.utils;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUitls {
/**
* 發送郵件的方法
* @param to :收件人
* @param code :激活碼
*/
public static void sendMail(String to,String code){
//獲得對象
Properties props = new Properties();
props.setProperty("mail.host", "localhost");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "111");
}
});
//創建郵件對象
Message message = new MimeMessage(session);
//設置發件人
try {
message.setFrom(new InternetAddress("[email protected]"));
//設置收件人
message.addRecipient(RecipientType.TO, new InternetAddress(to));
//抄送 CC 密送BCC
//設置標題
message.setSubject("來自XXX的官方激活郵件");
//設置郵件正文。
message.setContent("<h1>來自XXX的官方激活郵件!點擊鏈接完成激活操作。</h1><h3><a href='http://192.168.24.168:8080/shop8.2/user_active.action?code="+code+"'>http://192.168.24.168:8080/shop/user_active.action?code="+code+"</a></h3>", "text/html;charset=UTF-8");
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
//測試
public static void main(String[] args) {
sendMail("[email protected]","11111111111111");
}
}
</span>
4、運行結果
總結:這樣就完成了郵件發送的功能,驗證碼可以代碼隨機生成,需要郵箱驗證服務的功能,通過調用這個方法就可以進行驗證。