package com.vcfilm.mytest.action;
smtp 發送郵件
平時我們會使用一些功能,比如做用戶註冊發送郵件激活的時候,可以使用smtp服務,下面是使用的一個簡單例子:
package com.vcfilm.mytest.action;
package com.vcfilm.mytest.action;
import java.util.Properties;
import javax.mail.Authenticator;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Test {
public static void main(String[] args) throws MessagingException {
// 配置發送郵件的環境屬性
final Properties props = new Properties();// 表示SMTP發送郵件,需要進行身份驗證
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");// 發件人的賬號
props.put("mail.user", "***[email protected]");// 訪問SMTP服務時需要提供的密碼
props.put("mail.password", "r******");// 構建授權信息,用於進行SMTP進行身份驗證
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {// 用戶名、密碼
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};// 使用環境屬性和授權信息,創建郵件會話
Session mailSession = Session.getInstance(props, authenticator);// 創建郵件消息
MimeMessage message = new MimeMessage(mailSession);// 設置發件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);// 設置收件人
InternetAddress to = new InternetAddress("ron***iang@***.com");
message.setRecipient(RecipientType.TO, to);// 設置郵件標題
message.setSubject("測試郵件");// 設置郵件的內容體
message.setContent("<a href='http://localhost:8080/vctest/activate?user.name=33'>測試的HTML郵件</a>", "text/html;charset=UTF-8");// 發送郵件
Transport.send(message);
System.out.println("發送成功");
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.