郵件服務
阿新 • • 發佈:2021-07-20
郵件服務 簡訊驗證
-
匯入需要的jar包
-
設定一個我們的郵箱伺服器----作為傳送端
qq郵箱--》設定--》賬戶--》郵件服務(pop3等)--》開啟一個服務
使用步驟
1.發件人的郵箱跟密碼
public static String myEmailAccount = "*******";//郵箱地址
public static String myEmailPassword = "********";//開啟伺服器時的授權碼
2.建立連線物件,連線到郵件伺服器
Properties props = new Properties();
3.設定傳送郵件的基本引數
props.setProperty("mail.transport.protocol", "smtp"); // 使用的協議(JavaMail規範要求) // 網易163郵箱的 SMTP 伺服器地址為: smtp.163.com props.setProperty("mail.smtp.host", "smtp.qq.com"); // 發件人的郵箱的 SMTP 伺服器地址 props.setProperty("mail.smtp.auth", "true"); // 需要請求認證
4.設定傳送郵件的賬號和密碼
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//兩個引數分別是傳送郵件的賬戶和密碼
return new PasswordAuthentication(myEmailAccount,myEmailPassword);
}
});
5.郵件物件設定
//建立郵件物件 Message message = new MimeMessage(session); //設定發件人 message.setFrom(new InternetAddress(傳送郵件的賬號)); //設定收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress(收件人郵箱)); //設定主題 message.setSubject("這是一份測試郵件"); //設定郵件正文 第二個引數是郵件傳送的型別 message.setContent("要傳送的內容","text/html;charset=UTF-8");
6.傳送郵件
Transport.send(message);
整體程式碼
// 發件人的 郵箱 和 密碼(替換為自己的郵箱和密碼) // PS: 某些郵箱伺服器為了增加郵箱本身密碼的安全性,給 SMTP 客戶端設定了獨立密碼(有的郵箱稱為“授權碼”), // 對於開啟了獨立密碼的郵箱, 這裡的郵箱密碼必需使用這個獨立密碼(授權碼)。 public static String myEmailAccount = "#########";//郵箱地址 public static String myEmailPassword = "########";//開啟伺服器時的授權碼 /** * @Author Yuriki * @Description 傳送郵件 * @param to 給誰發 * @param text 傳送內容 * @return void * @Date 2021/7/20 */ public static void sendEmail(String to,String text) throws MessagingException { //建立連線物件,連線到郵件伺服器 Properties props = new Properties(); //設定傳送郵件的基本引數 props.setProperty("mail.transport.protocol", "smtp"); // 使用的協議(JavaMail規範要求) // 網易163郵箱的 SMTP 伺服器地址為: smtp.163.com props.setProperty("mail.smtp.host", "smtp.qq.com"); // 發件人的郵箱的 SMTP 伺服器地址 props.setProperty("mail.smtp.auth", "true"); // 需要請求認證 //設定傳送郵件的賬號和密碼 Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { //兩個引數分別是傳送郵件的賬戶和密碼 return new PasswordAuthentication(myEmailAccount,myEmailPassword); } }); //建立郵件物件 Message message = new MimeMessage(session); //設定發件人,第二個引數為傳送郵件的標題 message.setFrom(new InternetAddress(myEmailAccount,"人員管理系統","UTF-8")); //設定收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress(to)); //設定主題 message.setSubject("這是一份測試郵件"); //設定郵件正文 第二個引數是郵件傳送的型別 message.setContent(text,"text/html;charset=UTF-8"); //傳送一封郵件 Transport.send(message); }