java发送邮件的具体实现
首先是继承自javax.mail.Authenticator的一个具体类。getPasswordAuthentication()方法也就是构建一个PasswordAuthentication对象并返回,有点费解JAVA Mail这样的设计意图,可能javax.mail.Authenticator为我们提供了附加的保证安全的验证措施吧。
package com.mzule.simplemail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailAuthenticator extends Authenticator {
private String username;
private String 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;
public class MailSenderFactory {
private static SimpleMailSender serviceSms = null;
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();
}
}
}
}
}
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341