註冊成功傳送郵件
阿新 • • 發佈:2018-11-02
前提:確認匯入了jar包:mail.jar
*注:網易郵箱給網易郵箱發的較快。
MailUtils.java
package com.pb.utils; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; 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; import javax.mail.internet.MimeMessage.RecipientType; 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("176****
[email protected]", "w****2"); } }; Session session = Session.getInstance(props, auth); // 2.建立一個Message,它相當於是郵件內容 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("176****[email protected]")); // 設定傳送者 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); } }
呼叫者:
String emailMsg = "恭喜您註冊成功,請點選下面的連線進行啟用賬戶"
+ "<a href='http://localhost:9100/shop/active?
activeCode="+activeCode+"'>"
+ "http://localhost:9100/shop/active?activeCode="+activeCode+"</a>";
MailUtils.sendMail(user.getEmail(), emailMsg); 從表單獲取的使用者郵箱