java发送邮件的具体实现
首先是继承自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("invisible@126.com",
"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("invisible@qq.com");
recipients.add("invisible@gmail.com");
try {
for (string recipient : recipients) {
sms.send(recipient, "价格变动", "您关注的物品"
+ product.getname() + "降价了,由"
+ product.getprice() + "元降到" + price + "元,降幅达"
+ decrease + "元人民币。赶快购物吧。");
}
} catch (addressexception e) {
e.printstacktrace();
} catch (messagingexception e) {
e.printstacktrace();
}
}
}
}
}