使用原生Java Mail发送邮件程序。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 邮件发送工具
* <p/>
* Author : wangxp
* <p/>
* DateTime : 2016/1/13 14:10
*/
public class SendEmailUtil
{
private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailUtil.class);
/**
* The host name of the smtp server. REQUIRED.
*/
public static final String PROP_SMTP_HOST = "smtp_host";
/**
* smtp server port. Optional.
*/
public static final String PROP_SMTP_PORT = "smtp_port";
/**
* Enable TLS. Optional.
*/
public static final String PROP_TLS_ENABLE = "enable_tls";
/**
* Enable Auth. Optional.
*/
public static final String PROP_AUTH_ENABLE = "enable_auth";
/**
* Auth Username. Optional.
*/
public static final String PROP_AUTH_USERNAME = "username";
/**
* Auth Password. Optional.
*/
public static final String PROP_AUTH_PASSWORD = "password";
/**
* The e-mail address to send the mail to. REQUIRED.
*/
public static final String PROP_RECIPIENT = "recipient";
/**
* The e-mail address to cc the mail to. Optional.
*/
public static final String PROP_CC_RECIPIENT = "cc_recipient";
/**
* The e-mail address to claim the mail is from. REQUIRED.
*/
public static final String PROP_SENDER = "sender";
/**
* The e-mail address the message should say to reply to. Optional.
*/
public static final String PROP_REPLY_TO = "reply_to";
/**
* The subject to place on the e-mail. REQUIRED.
*/
public static final String PROP_SUBJECT = "subject";
/**
* The e-mail message body. REQUIRED.
*/
public static final String PROP_MESSAGE = "message";
/**
* The message content type. For example, "text/html". Optional.
*/
public static final String PROP_CONTENT_TYPE = "content_type";
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
static
{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
}
public static void send(Map<String, String> data) throws Exception
{
MailInfo mailInfo = populateMailInfo(data, createMailInfo());
getLogger().info("Sending message " + mailInfo);
try
{
MimeMessage mimeMessage = prepareMimeMessage(mailInfo);
Transport.send(mimeMessage);
}
catch (MessagingException e)
{
getLogger().error("Unable to send mail: " + mailInfo, e);
throw e;
}
}
protected static Logger getLogger()
{
return LOGGER;
}
protected static MimeMessage prepareMimeMessage(MailInfo mailInfo)
throws MessagingException
{
Session session = getMailSession(mailInfo);
MimeMessage mimeMessage = new MimeMessage(session);
Address[] toAddresses = InternetAddress.parse(mailInfo.getTo());
mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses);
if (mailInfo.getCc() != null)
{
Address[] ccAddresses = InternetAddress.parse(mailInfo.getCc());
mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses);
}
mimeMessage.setFrom(new InternetAddress(mailInfo.getFrom()));
if (mailInfo.getReplyTo() != null)
{
mimeMessage.setReplyTo(new InternetAddress[]{new InternetAddress(mailInfo.getReplyTo())});
}
mimeMessage.setSubject(mailInfo.getSubject());
mimeMessage.setSentDate(new Date());
setMimeMessageContent(mimeMessage, mailInfo);
return mimeMessage;
}
protected static void setMimeMessageContent(MimeMessage mimeMessage, MailInfo mailInfo)
throws MessagingException
{
if (mailInfo.getContentType() == null)
{
mimeMessage.setText(mailInfo.getMessage());
}
else
{
mimeMessage.setContent(mailInfo.getMessage(), mailInfo.getContentType());
}
}
protected static Session getMailSession(final MailInfo mailInfo) throws MessagingException
{
Properties properties = new Properties();
properties.put("mail.smtp.host", mailInfo.getSmtpHost());
if (null != mailInfo.getSmtpPort())
{
properties.put("mail.smtp.port", mailInfo.getSmtpPort());
}
if (Boolean.valueOf(mailInfo.getEnableTls()))
{
properties.put("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
}
else
{
properties.put("mail.smtp.starttls.enable", "false");
}
Authenticator authenticator = null;
if (Boolean.valueOf(mailInfo.getEnableAuth()))
{
properties.put("mail.smtp.auth", "true");
authenticator = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(mailInfo.getUsername(), mailInfo.getPassword());
}
};
}
else
{
properties.put("mail.smtp.auth", "false");
}
return Session.getDefaultInstance(properties, authenticator);
}
protected static MailInfo createMailInfo()
{
return new MailInfo();
}
protected static MailInfo populateMailInfo(Map<String, String> data, MailInfo mailInfo)
{
// Required parameters
mailInfo.setSmtpHost(getRequiredParm(data, PROP_SMTP_HOST, "PROP_SMTP_HOST"));
mailInfo.setTo(getRequiredParm(data, PROP_RECIPIENT, "PROP_RECIPIENT"));
mailInfo.setFrom(getRequiredParm(data, PROP_SENDER, "PROP_SENDER"));
mailInfo.setSubject(getRequiredParm(data, PROP_SUBJECT, "PROP_SUBJECT"));
mailInfo.setMessage(getRequiredParm(data, PROP_MESSAGE, "PROP_MESSAGE"));
// Optional parameters
mailInfo.setReplyTo(getOptionalParm(data, PROP_REPLY_TO));
mailInfo.setCc(getOptionalParm(data, PROP_CC_RECIPIENT));
mailInfo.setContentType(getOptionalParm(data, PROP_CONTENT_TYPE));
mailInfo.setSmtpPort(getOptionalParm(data, PROP_SMTP_PORT));
mailInfo.setEnableAuth(getOptionalParm(data, PROP_AUTH_ENABLE));
mailInfo.setEnableTls(getOptionalParm(data, PROP_TLS_ENABLE));
mailInfo.setUsername(getOptionalParm(data, PROP_AUTH_USERNAME));
mailInfo.setPassword(getOptionalParm(data, PROP_AUTH_PASSWORD));
return mailInfo;
}
protected static String getRequiredParm(Map<String, String> data, String property, String constantName)
{
String value = getOptionalParm(data, property);
if (value == null)
{
throw new IllegalArgumentException(constantName + " not specified.");
}
return value;
}
protected static String getOptionalParm(Map<String, String> data, String property)
{
String value = data.get(property);
if ((value != null) && (value.trim().length() == 0))
{
return null;
}
return value;
}
protected static class MailInfo
{
private String smtpHost;
private String smtpPort;
private String enableTls = "false";
private String enableAuth = "false";
private String username;
private String password;
private String to;
private String from;
private String subject;
private String message;
private String replyTo;
private String cc;
private String contentType;
@Override
public String toString()
{
return "'" + getSubject() + "' to: " + getTo();
}
public String getCc()
{
return cc;
}
public void setCc(String cc)
{
this.cc = cc;
}
public String getContentType()
{
return contentType;
}
public void setContentType(String contentType)
{
this.contentType = contentType;
}
public String getFrom()
{
return from;
}
public void setFrom(String from)
{
this.from = from;
}
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
public String getReplyTo()
{
return replyTo;
}
public void setReplyTo(String replyTo)
{
this.replyTo = replyTo;
}
public String getSmtpHost()
{
return smtpHost;
}
public void setSmtpHost(String smtpHost)
{
this.smtpHost = smtpHost;
}
public String getSubject()
{
return subject;
}
public void setSubject(String subject)
{
this.subject = subject;
}
public String getTo()
{
return to;
}
public void setTo(String to)
{
this.to = to;
}
public String getSmtpPort()
{
return smtpPort;
}
public void setSmtpPort(String smtpPort)
{
this.smtpPort = smtpPort;
}
public String getEnableTls()
{
return enableTls;
}
public void setEnableTls(String enableTls)
{
this.enableTls = enableTls;
}
public String getEnableAuth()
{
return enableAuth;
}
public void setEnableAuth(String enableAuth)
{
this.enableAuth = enableAuth;
}
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;
}
}
public static void main(String[] args) throws Exception
{
Map<String, String> sendEmailParams = new HashMap<>();
sendEmailParams.put(SendEmailUtil.PROP_SMTP_HOST, "smtp.exmail.qq.com");
sendEmailParams.put(SendEmailUtil.PROP_SMTP_PORT, "465");
sendEmailParams.put(SendEmailUtil.PROP_TLS_ENABLE, "true");
sendEmailParams.put(SendEmailUtil.PROP_AUTH_ENABLE, "true");
sendEmailParams.put(SendEmailUtil.PROP_AUTH_USERNAME, "kr@domain.com");
sendEmailParams.put(SendEmailUtil.PROP_AUTH_PASSWORD, "pass");
sendEmailParams.put(SendEmailUtil.PROP_RECIPIENT, "xx@qq.com");
sendEmailParams.put(SendEmailUtil.PROP_SENDER, "kr@domain.com");
sendEmailParams.put(SendEmailUtil.PROP_SUBJECT, "测试邮件主题");
sendEmailParams.put(SendEmailUtil.PROP_CONTENT_TYPE, "text/html; charset=\"utf-8\"");
sendEmailParams.put(SendEmailUtil.PROP_MESSAGE, "测试邮件内容");
SendEmailUtil.send(sendEmailParams);
}
}