public class Mail {
private String m_Host = "smtp.qq.com";
public String getHost() {
return m_Host;
}
public void setHost(String host) {
m_Host = host;
}
/**
* 发送邮件
*
* @param subject
* 邮件主题
* @param body
* 邮件内容
* @param addresses
* 目标地址
* @param myEmail
* 邮件发送者的邮箱地址
* @param myPwd
* 邮件发送者的邮箱密码
* @param myName
* 邮件发送者的姓名
* @return
*/
public boolean sendMail(String subject, String body,
List<String> addresses, String myEmail, String myPwd, String myName) {
boolean flag = true;
try {
Properties props = new Properties();// 获取系统环境
props.put("mail.smtp.host", m_Host);
props.put("mail.smtp.auth", "true");
Misc.getLogger().info(props);
Session session = Session.getDefaultInstance(props);
// 设置session,和邮件服务器进行通讯
MimeMessage message = new MimeMessage(session);
message.setContent("Hello", "text/plain");// 设置邮件格式
message.setSubject(subject);// 设置邮件主题
message.setText(body);// 设置邮件内容
message.setSentDate(new Date());// 设置邮件发送时间
Address address = new InternetAddress(myEmail, myName);
message.setFrom(address);// 设置邮件发送者的地址
Address[] toaddress = new InternetAddress[addresses.size()];// 设置邮件接收者的地址
for (int i = 0; i < addresses.size(); i++) {
toaddress[i] = new InternetAddress(addresses.get(i));
Misc.getLogger().info("send Email to :" + addresses.get(i));
}
Transport transport = session.getTransport("smtp");//不要用transport的静态方法,很容易出现问题
transport.connect(m_Host, myEmail, myPwd);
transport.sendMessage(message, toaddress);
transport.close();
Misc.getLogger().info("Send Mail success!");
} catch (MessagingException e) {
Misc.getLogger().info(e.getMessage());
flag = false;
} catch (UnsupportedEncodingException el) {
Misc.getLogger().info(el.getMessage());
flag = false;
}
return flag;
}
}
}