|
import javax.mail.*; |
|
import javax.mail.internet.InternetAddress; |
|
import javax.mail.internet.MimeMessage; |
|
import java.nio.charset.StandardCharsets; |
|
import java.util.List; |
|
import java.util.Properties; |
|
|
|
public class SMPTUtils { |
|
/** |
|
* 使用 163 举例 |
|
*/ |
|
private static final String HOST = "smtp.163.com"; |
|
private static final String PORT = "587"; |
|
private static final String USERNAME = "@163.com"; |
|
private static final String PASSWORD = ""; |
|
|
|
private static final String MIMETYPE_TEXT_HTML_UTF_8 = "text/html; charset=utf-8"; |
|
|
|
private static Properties prepareProperties() { |
|
Properties props = new Properties(); |
|
props.put("mail.smtp.host", HOST); |
|
props.put("mail.smtp.port", PORT); |
|
props.put("mail.smtp.auth", "true"); |
|
props.put("mail.smtp.ssl.enable", "true"); |
|
return props; |
|
} |
|
|
|
private static Session createSession() { |
|
Properties prop = prepareProperties(); |
|
|
|
return Session.getInstance(prop, new Authenticator() { |
|
@Override |
|
protected PasswordAuthentication getPasswordAuthentication() { |
|
return new PasswordAuthentication(USERNAME, PASSWORD); |
|
} |
|
}); |
|
} |
|
|
|
public static void sendMail(List<String> primaryRecipients, List<String> carbonCopyRecipients, String subject, String content) throws MessagingException { |
|
Session session = createSession(); |
|
session.setDebug(true); |
|
|
|
MimeMessage message = new MimeMessage(session); |
|
message.setFrom(new InternetAddress(USERNAME)); |
|
setRecipientsByList(message, Message.RecipientType.TO, primaryRecipients); |
|
setRecipientsByList(message, Message.RecipientType.CC, carbonCopyRecipients); |
|
message.setSubject(subject, StandardCharsets.UTF_8.name()); |
|
message.setContent(content, MIMETYPE_TEXT_HTML_UTF_8); |
|
|
|
Transport.send(message); |
|
} |
|
|
|
private static void setRecipientsByList(MimeMessage message, Message.RecipientType type, List<String> recipients) throws MessagingException { |
|
if (recipients == null) { |
|
return; |
|
} |
|
|
|
for (String recipient : recipients) { |
|
message.setRecipient(type, new InternetAddress(recipient)); |
|
} |
|
} |
|
} |