首先是繼承自javax.mail.Authenticator的一個具體類。getPasswordAuthentication()方法也就是構建一個PasswordAuthentication對象並返回,有點費解JAVA Mail這樣的設計意圖,可能是javax.mail.Authenticator為我們提供了附加的保證安全的驗證措施吧。
代碼如下package com.mzule.simplemail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
* 服務器郵箱登錄驗證
*
* @author MZULE
*
*/
public class MailAuthenticator extends Authenticator {
/**
* 用戶名(登錄郵箱)
*/
private String username;
/**
* 密碼
*/
private String password;
/**
* 初始化郵箱和密碼
*
* @param username 郵箱
* @param password 密碼
*/
public MailAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
String getPassword() {
return password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
}
調用上面的郵箱發送器,可以構建一個工廠類,工廠類可以封裝創建的過程,所以通過讀配置文件獲取郵箱用戶名,密碼都會變得十分方便。下面的代碼是我在寫觀察者模式的時候寫的,只是簡單演示了工廠類。
代碼如下package com.mzule.dp.observer.factory;
import com.mzule.dp.observer.constant.MailSenderType;
import com.mzule.simplemail.SimpleMailSender;
/**
* 發件箱工廠
*
* @author MZULE
*
*/
public class MailSenderFactory {
/**
* 服務郵箱
*/
private static SimpleMailSender serviceSms = null;
/**
* 獲取郵箱
*
* @param type 郵箱類型
* @return 符合類型的郵箱
*/
public static SimpleMailSender getSender(MailSenderType type) {
if (type == MailSenderType.SERVICE) {
if (serviceSms == null) {
serviceSms = new SimpleMailSender("[email protected]",
"hidden");
}
return serviceSms;
}
return null;
}
}
發送郵件,還是觀察者模式DEMO裡面的代碼,呼呼。
代碼如下package com.mzule.dp.observer.observer;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import com.mzule.dp.observer.constant.MailSenderType;
import com.mzule.dp.observer.factory.MailSenderFactory;
import com.mzule.dp.observer.po.Product;
import com.mzule.simplemail.SimpleMailSender;
public class ProductPriceObserver implements Observer {
@Override
public void update(Observable obj, Object arg) {
Product product = null;
if (obj instanceof Product) {
product = (Product) obj;
}
if (arg instanceof Float) {
Float price = (Float) arg;
Float decrease = product.getPrice() - price;
if (decrease > 0) {
// 發送郵件
SimpleMailSender sms = MailSenderFactory
.getSender(MailSenderType.SERVICE);
List<String> recipients = new ArrayList<String>();
recipients.add("[email protected]");
recipients.add("[email protected]");
try {
for (String recipient : recipients) {
sms.send(recipient, "價格變動", "您關注的物品"
+ product.getName() + "降價了,由"
+ product.getPrice() + "元降到" + price + "元,降幅達"
+ decrease + "元人民幣。趕快購物吧。");
}
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
}