message.setRecipients(RecipientType.TO, addresses);
// 设置主题
message.setSubject(subject);
// 设置邮件内容
message.setContent(content.toString(),
"text/html;charset=utf-8"
);
// 发送
Transport.send(message);
}
/**
* 发送邮件
*
* @param recipient
* 收件人邮箱地址
* @param mail
* 邮件对象
* @throws AddressException
* @throws MessagingException
*/
public
void
send(String recipient, SimpleMail mail)
throws
AddressException, MessagingException {
send(recipient, mail.getSubject(), mail.getContent());
}
/**
* 群发邮件
*
* @param recipients
* 收件人们
* @param mail
* 邮件对象
* @throws AddressException
* @throws MessagingException
*/
public
void
send(List<String> recipients, SimpleMail mail)
throws
AddressException, 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里面的代码,呼呼。
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();
}
}
}
}
}
|