67,549
社区成员




/**
* 发送HTML格式的邮件
*
* @param mails
* 收件人地址组
* @param content
* 邮件正文
* @param subject
* 邮件标题
* @throws MailException
*/
public void sendHTMLMails(String[] mails, String subject, String content)
throws MailException {
MimeMessage message = sender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, false,
"UTF-8");
StringBuffer sb = new StringBuffer();
// 解析收件人地址
if (mails != null && mails.length > 0) {
for (String m : mails) {
sb.append(m + ",");
}
helper.setTo(InternetAddress.parse(sb.toString()));
}
helper.setSubject(subject);
helper.setText(content, true); // true表示为HTML邮件
helper.setFrom(new InternetAddress(from, MimeUtility.encodeText(alias,
"UTF-8", "b")));
sender.send(message);
} catch (MessagingException e) {
throw new MailException("发送HTML格式邮件时出错,错误信息:" + e.getMessage());
} catch (UnsupportedEncodingException e) {
throw new MailException("发送HTML格式邮件时出错,错误信息:" + e.getMessage());
}
}
/**
* @param reply
* 回复地址
* @param to
* 收信人地址
* @param subject
* 邮件标题
* @param email
* 邮件正文
*/
public static boolean sendHtmlEmail(String reply, String to,
String subject, String email) {
String smtpServer = Constants.Email_SMTP; // SMTP服务器名
String name = Constants.Email_LoginName; // 邮箱登录名
String passWord = Constants.Email_LoginPassword; // 邮箱密码
Properties props = new Properties();
Session sendMailSession;
Transport transport;
sendMailSession = Session.getInstance(props);
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.port", 465);
props.put("mail.smtp.auth", "true");
MimeMessage message = new MimeMessage(sendMailSession);
try {
message.setFrom(new InternetAddress("Mingoe<"
+ Constants.Email_Server + ">"));
InternetAddress[] address = InternetAddress.parse(to);
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
// 设置邮件发送时间,将来要和服务器时间互转
Calendar clientCal = Calendar.getInstance();
message.setSentDate(clientCal.getTime());
BodyPart mdp = new MimeBodyPart(); // 新建一个存放信件内容的BodyPart对象
if (!isYahooEmail(to)) {
mdp.setContent(email, "text/html;charset=UTF-8"); // 给BodyPart对象设置内容和格式/编码方式
} else {
mdp.setContent(email, "text/html;charset=GBK"); // 给BodyPart对象设置内容和格式/编码方式
}
Multipart mp = new MimeMultipart(); // 新建一个MimeMultipart对象用来存放BodyPart对象
mp.addBodyPart(mdp); // 将BodyPart加入到MimeMultipart对象中
message.setContent(mp); // 把mm作为消息对象的内容
transport = sendMailSession.getTransport("smtp");
transport.connect(smtpServer, name, passWord);
message.saveChanges();
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return true;
} catch (AddressException addressException) {
// addressException.printStackTrace();
return false;
} catch (MessagingException messagingException) {
// messagingException.printStackTrace();
return false;
} catch (Exception e) {
// e.printStackTrace();
return false;
}
}