JavaMail--群发HTML邮件

上一篇博客将的是emailHtml来发送html格式的邮件,那么现在我们就用javaMail来群发一份html格式的邮件

package com.tgb.email;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class MailUtils {
    private static String host;
    private static String username;
    private static String password;
    private static String from;
    private static String nick;

    static {
        try {
            // Test Data
            host = "smtp.163.com";
            username = "***@163.com"; //用户名,一般就是咱们的邮箱地址
            password = "***";          //登陆密码
            //nick + from 组成邮箱的发件人信息
            from = "****@163.com";     //邮箱账号
            nick = "ermu测试邮件";          //发件人名称    

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送邮件
     * 
     * @param to
     *            收件人列表,以","分割
     * @param subject
     *            标题
     * @param body
     *            内容
     * @param filepath
     *            附件列表,无附件传递null
     * @return
     * @throws MessagingException
     * @throws AddressException
     * @throws UnsupportedEncodingException
     */
    public static boolean sendMail(String to, String subject, String body)
            throws AddressException, MessagingException,
            UnsupportedEncodingException {
        // 参数修饰
        if (body == null) {
            body = "";
        }
        if (subject == null) {
            subject = "无主题";
        }
        // 创建Properties对象
        Properties props = System.getProperties();
        // 创建信件服务器
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true"); // 通过验证
        // 得到默认的对话对象
        Session session = Session.getDefaultInstance(props, null);
        // 创建一个消息,并初始化该消息的各项元素
        MimeMessage msg = new MimeMessage(session);
        nick = MimeUtility.encodeText(nick);
        msg.setFrom(new InternetAddress(nick + "<" + from + ">"));


        msg.setText(body, "UTF-8");
        // 创建收件人列表
        if (to != null && to.trim().length() > 0) {
            String[] arr = to.split(",");
            int receiverCount = arr.length;
            if (receiverCount > 0) {
                InternetAddress[] address = new InternetAddress[receiverCount];
                for (int i = 0; i < receiverCount; i++) {
                    address[i] = new InternetAddress(arr[i]);
                }
                msg.addRecipients(Message.RecipientType.TO, address);
                msg.setSubject(subject);
                // 后面的BodyPart将加入到此处创建的Multipart中

                //设置html内容
                //MimeMultipart是一个容器类,包含MimeBodyPart类型的对象
                Multipart mainPart = new MimeMultipart();
                //创建一个包含HTML内容的MimeBodyPart
                MimeBodyPart messageBodyPart = new MimeBodyPart();

                msg.setContent(mainPart);
                //设置HTML内容
                messageBodyPart.setContent(body,"text/html; charset=utf-8");
                mainPart.addBodyPart(messageBodyPart);

                //将MimeMultipart对象设置为邮件内容   
                msg.setContent(mainPart);

                 Transport transport = session.getTransport("smtp");
                transport.connect(host, username, password);
                transport.sendMessage(msg,
                        msg.getRecipients(Message.RecipientType.TO));
                transport.close();
                return true;
            } else {
                System.out.println("None receiver!");
                return false;
            }
        } else {
            System.out.println("None receiver!");
            return false;
        }
    }

    public static void main(String[] args) throws AddressException,
            UnsupportedEncodingException, MessagingException {
        StringBuffer demo = new StringBuffer();  
        demo.append("")  
        .append("")  
        .append("")  
        .append("")  
        .append("测试邮件")  
        .append("")  
        .append("")  
        .append("")  
        .append("大家好,这里是测试Demo")  
        .append("")  
        .append("");  

        sendMail("[email protected],[email protected]", "实习验收", demo.toString());
    }
}

JavaMail--群发HTML邮件_第1张图片

你可能感兴趣的:(J2EE,html,邮件,javamail)