package mail;
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 {
//email:郵件發給誰 subject:主題 emailMsg:郵件的內容
public static void sendMail(String email, String subject, 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("賬號", "密碼或者是授權碼");//發郵件的賬號的驗證
}
};
Session session = Session.getInstance(props, auth);
// 2.創建一個Message,它相當於是郵件內容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("****@java.com")); // 設置發送者
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設置發送方式與接收者
message.setSubject(subject);//郵件的主題
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.創建 Transport用於將郵件發送
Transport.send(message);
}
}
MailUtils工具類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.