JAVA邮件发送的简单实现(三)

2014-11-24 03:07:59 · 作者: · 浏览: 6
eption, MessagingException {

send(recipients, mail.getSubject(), mail.getContent());

}

}

3、调用上面的邮箱发送器,可以构建一个工厂类,工厂类可以封装创建的过程,所以通过读配置文件获取邮箱用户名,密码都会变得十分方便。下面的代码是我在写观察者模式的时候写的,只是简单演示了工厂类。

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;

}

}

4、发送邮件,还是观察者模式DEMO里面的代码,呼呼。

view sourceprint

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 recipients = new ArrayList();

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();

}

}

}

}

}

5、剩下的就是去查看邮件是否发送成功了。呼呼~

摘自 小瓶子