使用Java Mail发送邮件

使用原生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);
    }
}


/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值