package com.lobo.server.common;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.lobo.server.db.entity.LoboDeviceInspect;
public class JavaMail {
private Properties properties;
private Session mailSession;
private MimeMessage mailMessage;
private Transport trans;
public JavaMail() {
}
public boolean sendMail(Object obj) {
try {
LoboDeviceInspect ld = (LoboDeviceInspect)obj;
String name = ld.getLoboMoveDevice().getDeviceName();
String ip = ld.getLanAddr();
String userDate = ld.getUserDate().toString();
String smtpHost = this.readValue("smtpHost");
String from = this.readValue("from");;
String to = this.readValue("to");;
final String userName = this.readValue("userName");
final String password = this.readValue("password");
if(smtpHost==null || from==null || to==null ||userName==null || password==null){
return false;
}
properties = new Properties();
//设置邮件服务器
properties.put("mail.smtp.host", smtpHost);
//验证
properties.put("mail.smtp.auth", "true");
//根据属性新建一个邮件会话
mailSession = Session.getInstance(properties,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
// mailSession.setDebug(true);
//建立消息对象
mailMessage = new MimeMessage(mailSession);
//发件人
mailMessage.setFrom(new InternetAddress(from));
//收件人
mailMessage.setRecipient(MimeMessage.RecipientType.TO,
new InternetAddress(to));
//主题
mailMessage.setSubject("编码为:"+name+" 的设备在使用!");
//内容
mailMessage.setText("有设备在使用,详细内容如下:"
+"编码为:"+name+";"
+"主机IP为:"+ip+";"
+"使用时间为:"+userDate+"。");
//发信时间
mailMessage.setSentDate(new Date());
//存储信息
mailMessage.saveChanges();
//
trans = mailSession.getTransport("smtp");
//发送
trans.send(mailMessage);
trans.close();
return true;
} catch (Exception e) {
// e.printStackTrace();
return false;
} finally {
}
}
//根据key读取value
public String readValue(String key) {
Properties props = new Properties();
try {
String filePath = this.getClass().getResource("/").getPath();
InputStream in = new BufferedInputStream(new FileInputStream(filePath.replace("%20", " ")+"/sendMail.properties"));
props.load(in);
String value = props.getProperty(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
sendMail.properties文件放在src包下,内容为:
smtpHost=smtp.sohu.com
from=lobo07@sohu.com
to=lobo04@sina.com
userName=lobo07
password=lobo07