java mail 通用类

来源:互联网 发布:混血失败知乎 编辑:程序博客网 时间:2024/05/21 06:45

package com.citi.tool;

import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class CliffMailHelper {

    // define the default smtp host
    private static String SMTP_HOST;

    // define the default from address
    private static String FROM_ADDR;

    // define the default to address
    private static String TO_ADDR;

    // define the default cc address
    private static String CC_ADDR;

    // get the log instance from factory
    static CliffLogWriter log = new CliffLogWriter(CliffMailHelper.class
            .getName());

    /**
     * set Mail Properties
     *
     * @param smtpHost
     * @param fromAddr
     * @param toAddr
     * @param ccAddr
     */
    public static void loadMailProperties(Properties p) {

        SMTP_HOST = p.getProperty("mail.host");
        FROM_ADDR = p.getProperty("mail.from");
        TO_ADDR = p.getProperty("mail.to");

        log.info("Host : [" + SMTP_HOST + "] Mail From : [" + FROM_ADDR
                + "] Mail To : [" + TO_ADDR + "]");

    }

    /**
     * send mail
     *
     * @param subject
     * @param message
     * @throws Exception
     */
    public static void sendMail(String subject, String message)
            throws Exception {
        sendMail(FROM_ADDR, TO_ADDR, CC_ADDR, subject, message);
    }

    /**
     * send mail
     *
     * @param from
     * @param to
     * @param cc
     * @param subject
     * @param message
     * @throws Exception
     */
    public static void sendMail(String from, String to, String cc,
            String subject, String message) throws Exception {

        try {
            // Create properties, get Session
            Properties props = new Properties();

            // put mail host
            props.put("mail.smtp.host", SMTP_HOST);

            log.info("subject:" + subject);

            // create session
            Session session = Session.getInstance(props);

            // Instantiate a message
            Message msg = new MimeMessage(session);

            // Set message attributes
            msg.setFrom(new InternetAddress(from));

            // covert mail address
            InternetAddress[] toAddress = getAddresses(to);
            InternetAddress[] ccAddress = getAddresses(cc);

            // set the to address and cc address
            msg.setRecipients(Message.RecipientType.TO, toAddress);
            msg.setRecipients(Message.RecipientType.CC, ccAddress);

            // set the type of content
            msg.setContent(message, "text/html");

            // set the mail subject
            msg.setSubject(subject);

            // set mail date
            msg.setSentDate(new Date());

            // send mail
            Transport.send(msg);

            log.info("Successfully sent the email from " + from + " to " + to
                    + " cc " + cc);

        } catch (Exception e) {
            log.error("Failed sent the email from " + from + " to " + to
                    + " cc " + cc, e);
            throw e;
        }
    }

    /**
     * Gets InternetAddress[] from a string. The addresses in the string should
     * be separated by semicolon.
     *
     * @param addressGroup
     * @return
     */
    private static InternetAddress[] getAddresses(String addressGroup) {

        // check the parameter
        if (addressGroup == null)
            return null;

        // split the address
        StringTokenizer st = new StringTokenizer(addressGroup, ";");

        Vector<String> v = new Vector<String>();

        // split addresses from addressGroup string.
        if (st.countTokens() > 0) {
            while (st.hasMoreTokens()) {
                String address = st.nextToken();
                if (!("".equals(address.trim()))) {
                    v.add(address);
                }
            }
        }

        // parse address string to InternetAddress.
        InternetAddress[] addresses = new InternetAddress[v.size()];

        for (int i = 0; i < addresses.length; i++) {
            try {
                addresses[i] = new InternetAddress((String) v.get(i));
            } catch (AddressException e) {
                log.error("Parse email Address fialed.", e);
            }
        }
        return addresses;
    }

}

原创粉丝点击