Created
November 27, 2012 05:36
-
-
Save vivisidea/4152560 to your computer and use it in GitHub Desktop.
using javax.mail api to send emails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 发送邮件. | |
* @param toAddrs | |
* @param subject | |
* @param content | |
* @param files | |
*/ | |
public static void sendMail(List<String> toAddrs, String subject, String content, List<String> files) { | |
if(CollectionUtils.isEmpty(toAddrs)){ | |
return; | |
} | |
try { | |
Properties props = new Properties(); | |
// set smtp server | |
props.setProperty("mail.transport.protocol", "smtp"); | |
props.setProperty("mail.smtp.host", SMTP_SERVER); | |
props.setProperty("mail.smtp.auth", "true"); | |
// props.put("mail.debug", "true"); | |
// get session | |
Authenticator auth = new Authenticator() { | |
protected PasswordAuthentication getPasswordAuthentication() { | |
return new PasswordAuthentication(AUTH_USER, AUTH_PASSWORD); | |
} | |
}; | |
Session session = Session.getDefaultInstance(props, auth); | |
// session.setDebug(true); | |
MimeMessage message = new MimeMessage(session); | |
message.setFrom(new InternetAddress(SENDER)); | |
// to list | |
InternetAddress[] addresses = new InternetAddress[toAddrs.size()]; | |
for (int i = 0; i < toAddrs.size(); i++) { | |
addresses[i] = new InternetAddress(toAddrs.get(i)); | |
} | |
message.setRecipients(Message.RecipientType.TO, addresses); | |
message.setSubject(subject); | |
Multipart mp = new MimeMultipart(); | |
MimeBodyPart mbp = new MimeBodyPart(); | |
mbp.setContent(content, "text/html; charset=GBK"); | |
mp.addBodyPart(mbp); | |
if (CollectionUtils.isNotEmpty(files)) { | |
for (String file : files) { | |
if (StringUtils.isBlank(file)) { | |
continue; | |
} | |
FileDataSource fds = new FileDataSource(file); | |
mbp = new MimeBodyPart(); | |
mbp.setDataHandler(new DataHandler(fds)); | |
mbp.setFileName(MimeUtility.encodeText(fds.getName(), "GBK", "B")); | |
mp.addBodyPart(mbp); | |
} | |
} | |
message.setContent(mp); | |
message.setSentDate(new Date()); | |
message.saveChanges(); | |
Transport.send(message); | |
} catch (Exception e) { | |
logger.error("发送邮件失败" + e.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment