/**
* @category 自定义主题内容发送
* @param subject 主题
* @param body 内容
* @param to 目标邮箱
* @throws MessagingException
*/
public static void sendEmail(String subject, String body, String to) throws MessagingException{
LoginMail lm = new LoginMail(USERNAME, PASSWORD);
// 创建session
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", EMAIL_HOST);
Session session = Session.getDefaultInstance(props, lm);
// 创建 message
Message msg = new MimeMessage(session);
// 设置发送源地址
msg.setFrom(new InternetAddress(USERNAME));
// 多用户分解
StringTokenizer st = new StringTokenizer(to, ",");
String[] recipients = new String[st.countTokens()];
int rc = 0;
while (st.hasMoreTokens())
recipients[rc++] = st.nextToken();
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// 设置邮件主题并发送邮件
msg.setSubject(subject);
msg.setContent(body, "text/html;charset=utf-8");
Transport.send(msg);
}
/**
*
* @author zhangkun@leju.com
* @description 验证邮箱用户类
* @CreateTime 2015 2015年7月31日 下午4:25:56
*/
class LoginMail extends Authenticator {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
public LoginMail(String username, String password) {
this.username = username;
this.password = password;
}
}
转载于:https://my.oschina.net/ssrs2202/blog/493855