java web邮件发送实例

468 篇文章 0 订阅
317 篇文章 0 订阅
java web邮件发送实例

        邮件发送工具类,这里使用了多个发送者进行轮询,每次选择发送频次最低的发送者进行发送,目的是为了防止同一发送方发送的过于频繁被屏蔽。使用的java mail版本是1.4.7

        maven配置如下:

Xml代码 复制代码  收藏代码
  1. <dependency>  
  2.             <groupId>javax.mail</groupId>  
  3.             <artifactId>mail</artifactId>  
  4.             <version>1.4.7</version>  
  5. </dependency>  
<dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
</dependency>

        发送方封装类

 

Java代码 复制代码  收藏代码
  1. package com.special.utils.mail;  
  2.   
  3. /** 
  4.  * file MailInfo 
  5.  * 邮件发送者的模型,实现comparable接口,根据发送次数比较大小 
  6.  * 
  7.  * @author ds 
  8.  * @version 1.0 2015 
  9.  *          date 15-3-9 
  10.  */  
  11. public class MailInfo implements Comparable<MailInfo> {  
  12.     /** 
  13.      * 发送的主机地址 
  14.      */  
  15.     String hostName;  
  16.     /** 
  17.      * 发送人邮箱 
  18.      */  
  19.     String userName;  
  20.     /** 
  21.      * 发送人邮箱密码 
  22.      */  
  23.     String password;  
  24.     /** 
  25.      * 该发送方发送邮件次数 
  26.      */  
  27.     Integer count = 0;  
  28.   
  29.     public int compareTo(MailInfo other) {  
  30.         int o = other.getCount() == null ? 0 : other.getCount();  
  31.         return count - o;  
  32.     }  
  33.   
  34.     /** 
  35.      * 邮件发送类型 
  36.      */  
  37.     enum MailType {  
  38.         HTML,  
  39.         TEXT  
  40.     }  
  41.   
  42.     /** 
  43.      * 无参构造函数 
  44.      */  
  45.     public MailInfo() {  
  46.     }  
  47.   
  48.     /** 
  49.      * 含参数构造函数 
  50.      * 
  51.      * @param hostName 服务器主机SMTP地址 
  52.      * @param userName 发送者邮箱 
  53.      * @param password 发送者邮箱密码 
  54.      */  
  55.     public MailInfo(String hostName, String userName, String password) {  
  56.         this.hostName = hostName;  
  57.         this.userName = userName;  
  58.         this.password = password;  
  59.     }  
  60.   
  61.     public String getHostName() {  
  62.         return hostName;  
  63.     }  
  64.   
  65.     public void setHostName(String hostName) {  
  66.         this.hostName = hostName;  
  67.     }  
  68.   
  69.     public String getUserName() {  
  70.         return userName;  
  71.     }  
  72.   
  73.     public void setUserName(String userName) {  
  74.         this.userName = userName;  
  75.     }  
  76.   
  77.     public String getPassword() {  
  78.         return password;  
  79.     }  
  80.   
  81.     public void setPassword(String password) {  
  82.         this.password = password;  
  83.     }  
  84.   
  85.     public Integer getCount() {  
  86.         return count;  
  87.     }  
  88.   
  89.     public void setCount(Integer count) {  
  90.         this.count = count;  
  91.     }  
  92.   
  93.     public String toString() {  
  94.         return hostName + ":" + userName + ":" + count;  
  95.     }  
  96.   
  97. }  
package com.special.utils.mail;

/**
 * file MailInfo
 * 邮件发送者的模型,实现comparable接口,根据发送次数比较大小
 *
 * @author ds
 * @version 1.0 2015
 *          date 15-3-9
 */
public class MailInfo implements Comparable<MailInfo> {
    /**
     * 发送的主机地址
     */
    String hostName;
    /**
     * 发送人邮箱
     */
    String userName;
    /**
     * 发送人邮箱密码
     */
    String password;
    /**
     * 该发送方发送邮件次数
     */
    Integer count = 0;

    public int compareTo(MailInfo other) {
        int o = other.getCount() == null ? 0 : other.getCount();
        return count - o;
    }

    /**
     * 邮件发送类型
     */
    enum MailType {
        HTML,
        TEXT
    }

    /**
     * 无参构造函数
     */
    public MailInfo() {
    }

    /**
     * 含参数构造函数
     *
     * @param hostName 服务器主机SMTP地址
     * @param userName 发送者邮箱
     * @param password 发送者邮箱密码
     */
    public MailInfo(String hostName, String userName, String password) {
        this.hostName = hostName;
        this.userName = userName;
        this.password = password;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    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 Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public String toString() {
        return hostName + ":" + userName + ":" + count;
    }

}

          邮件发送类

Java代码 复制代码  收藏代码
  1. package com.special.utils.mail;  
  2.   
  3. import org.apache.commons.logging.Log;  
  4. import org.apache.commons.logging.LogFactory;  
  5.   
  6. import javax.mail.*;  
  7. import javax.mail.internet.InternetAddress;  
  8. import javax.mail.internet.MimeBodyPart;  
  9. import javax.mail.internet.MimeMessage;  
  10. import javax.mail.internet.MimeMultipart;  
  11. import java.util.*;  
  12.   
  13. /** 
  14.  * file MailUtil 
  15.  * 使用JAVA mail进行邮件发送的工具类 
  16.  * 
  17.  * @author ds 
  18.  * @version 1.0 2015 
  19.  *          date 15-3-9 
  20.  */  
  21. public class MailUtil {  
  22.     protected static Log logger = LogFactory.getLog("com.special.utils.mail.MailUtil");  
  23.     /** 
  24.      * 存放发送方信息 
  25.      */  
  26.     private static List<MailInfo> mailFromList = new ArrayList<MailInfo>();  
  27.   
  28.     /** 
  29.      * 标记初始化发送方信息 
  30.      */  
  31.     private static boolean flag = true;  
  32.     /** 
  33.      * 邮件发送发生异常后重复发送的次数 
  34.      */  
  35.     private static Integer exceptionCount = 5;  
  36.   
  37.     /** 
  38.      * 初始化发送方信息 
  39.      * 
  40.      * @param list 发送方列表 
  41.      */  
  42.     public static void init(List<MailInfo> list) {  
  43.         if (flag) {  
  44.             mailFromList = list;  
  45.             flag = false;  
  46.         }  
  47.     }  
  48.   
  49.     /** 
  50.      * 发送邮件 
  51.      * 
  52.      * @param subject 邮件主题 
  53.      * @param type    邮件类型,html或者文本 
  54.      * @param content 邮件内容 
  55.      * @param to      收件人,有逗号隔开 
  56.      * @param cc      抄送,逗号隔开 
  57.      * @param bcc     暗送,逗号隔开 
  58.      * @return boolean true 发送成功 false 发送失败 
  59.      */  
  60.     public static boolean send(String subject, MailInfo.MailType type, String content, String to, String cc, String bcc) {  
  61.         boolean result = true;  
  62.         //首先列表排序  
  63.         Collections.sort(mailFromList);  
  64.         //获取发送频率最小的一个值  
  65.         final MailInfo mailInfo = mailFromList.get(0) == null ? new MailInfo() : mailFromList.get(0);  
  66.         logger.info(mailInfo.toString());  
  67.         /** 
  68.          * 每使用一次mail服务器就递增一次发送次数,而不是发送成功之后才递增, 
  69.          * 这样做的目的是避免某一台mail服务器故障后无法发送邮件但永远频次最低, 
  70.          * 故永远选择这台故障机发送,所带来的问题 
  71.          */  
  72.         mailInfo.setCount(mailInfo.getCount() + 1);  
  73.         // 以下为发送程序,用户无需改动  
  74.         Properties props = new Properties();  
  75.         props.put("mail.smtp.host", mailInfo.getHostName());  
  76.         //身份验证,一般邮件服务器都需要身份验证  
  77.         props.put("mail.smtp.auth""true");  
  78.         Session ssn = Session.getInstance(props, new Authenticator() {  
  79.             @Override  
  80.             protected PasswordAuthentication getPasswordAuthentication() {  
  81.                 return new PasswordAuthentication(mailInfo.getUserName(), mailInfo.getPassword());    //To change body of overridden methods use File | Settings | File Templates.  
  82.             }  
  83.   
  84.         });  
  85.         MimeMessage message = new MimeMessage(ssn);  
  86.         InternetAddress fromAddress;  
  87.         try {  
  88.             fromAddress = new InternetAddress(mailInfo.getUserName());  
  89.             message.setFrom(fromAddress);  
  90.             //收件人,以逗号隔开  
  91.             message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));  
  92.             //抄送,以逗号隔开  
  93.             if (null != cc && !"".equals(cc)) {  
  94.                 message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));  
  95.             }  
  96.             //暗送,逗号隔开  
  97.             if (null != bcc && !"".equals(bcc)) {  
  98.                 message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));  
  99.             }  
  100.             message.setSubject(subject);  
  101.             switch (type) {  
  102.                 case HTML:  
  103.                     MimeBodyPart mbp = new MimeBodyPart();  
  104.                     // 设定邮件内容的类型为 text/plain 或 text/html  
  105.                     mbp.setContent(content, "text/html;charset=UTF-8");  
  106.                     Multipart mp = new MimeMultipart();  
  107.                     mp.addBodyPart(mbp);  
  108.                     message.setContent(mp);  
  109.                     break;  
  110.                 case TEXT:  
  111.                     //发送文本邮件  
  112.                     message.setText(content);  
  113.                     break;  
  114.             }  
  115.             message.setSentDate(new Date());  
  116.             //发送邮件,还有另外一种写法  
  117.             /*Transport transport = ssn.getTransport("smtp"); 
  118.             transport.connect(mailInfo.getHostName(), mailInfo.getUserName(), mailInfo.getPassword()); 
  119.             transport.sendMessage(message, message.getAllRecipients()); 
  120.             transport.close();*/  
  121.             Transport.send(message);  
  122.             logger.info("mail send successfully from " + mailInfo.getUserName() + " to " + to + " and cc to " + cc);  
  123.         } catch (Exception e) {  
  124.             result = false;  
  125.             synchronized (exceptionCount) {  
  126.                 if (exceptionCount <= 0) {  
  127.                     exceptionCount = 5;  
  128.                 } else {  
  129.                     exceptionCount--;  
  130.                     if (send(subject, type, content, to, cc, bcc)) {  
  131.                         result = true;  
  132.                         exceptionCount = 5;  
  133.                     }  
  134.                     logger.info("mail send failure ,from " + mailInfo.getUserName() + " to " + to);  
  135.                 }  
  136.             }  
  137.             e.printStackTrace();  
  138.         }  
  139.   
  140.         return result;  
  141.     }  
  142.   
  143.     public boolean test() {  
  144.         boolean r = true;  
  145.         try {  
  146.             logger.info(1 / 0);  
  147.         } catch (Exception e) {  
  148.             r = false;  
  149.             e.printStackTrace();  
  150.         }  
  151.         return r;  
  152.     }  
  153.   
  154.     public static void main(String[] args) {  
  155.         MailInfo info;  
  156.         String hostName = "mail.sino****.com.cn";  
  157.         info = new MailInfo(hostName, "ds1@mail.com.cn""pwd1");  
  158.         mailFromList.add(info);  
  159.         info = new MailInfo(hostName, "ds@mail.com.cn""pwd");  
  160.         mailFromList.add(info);  
  161.   
  162.   
  163.         boolean r = MailUtil.send("test", MailInfo.MailType.HTML, "<div style=\"color:red\">from new mail test</div>""8****@qq.com""""");  
  164.         logger.info(r);  
  165.     }  
  166. }  
package com.special.utils.mail;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.*;

/**
 * file MailUtil
 * 使用JAVA mail进行邮件发送的工具类
 *
 * @author ds
 * @version 1.0 2015
 *          date 15-3-9
 */
public class MailUtil {
    protected static Log logger = LogFactory.getLog("com.special.utils.mail.MailUtil");
    /**
     * 存放发送方信息
     */
    private static List<MailInfo> mailFromList = new ArrayList<MailInfo>();

    /**
     * 标记初始化发送方信息
     */
    private static boolean flag = true;
    /**
     * 邮件发送发生异常后重复发送的次数
     */
    private static Integer exceptionCount = 5;

    /**
     * 初始化发送方信息
     *
     * @param list 发送方列表
     */
    public static void init(List<MailInfo> list) {
        if (flag) {
            mailFromList = list;
            flag = false;
        }
    }

    /**
     * 发送邮件
     *
     * @param subject 邮件主题
     * @param type    邮件类型,html或者文本
     * @param content 邮件内容
     * @param to      收件人,有逗号隔开
     * @param cc      抄送,逗号隔开
     * @param bcc     暗送,逗号隔开
     * @return boolean true 发送成功 false 发送失败
     */
    public static boolean send(String subject, MailInfo.MailType type, String content, String to, String cc, String bcc) {
        boolean result = true;
        //首先列表排序
        Collections.sort(mailFromList);
        //获取发送频率最小的一个值
        final MailInfo mailInfo = mailFromList.get(0) == null ? new MailInfo() : mailFromList.get(0);
        logger.info(mailInfo.toString());
        /**
         * 每使用一次mail服务器就递增一次发送次数,而不是发送成功之后才递增,
         * 这样做的目的是避免某一台mail服务器故障后无法发送邮件但永远频次最低,
         * 故永远选择这台故障机发送,所带来的问题
         */
        mailInfo.setCount(mailInfo.getCount() + 1);
        // 以下为发送程序,用户无需改动
        Properties props = new Properties();
        props.put("mail.smtp.host", mailInfo.getHostName());
        //身份验证,一般邮件服务器都需要身份验证
        props.put("mail.smtp.auth", "true");
        Session ssn = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailInfo.getUserName(), mailInfo.getPassword());    //To change body of overridden methods use File | Settings | File Templates.
            }

        });
        MimeMessage message = new MimeMessage(ssn);
        InternetAddress fromAddress;
        try {
            fromAddress = new InternetAddress(mailInfo.getUserName());
            message.setFrom(fromAddress);
            //收件人,以逗号隔开
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            //抄送,以逗号隔开
            if (null != cc && !"".equals(cc)) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
            //暗送,逗号隔开
            if (null != bcc && !"".equals(bcc)) {
                message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
            }
            message.setSubject(subject);
            switch (type) {
                case HTML:
                    MimeBodyPart mbp = new MimeBodyPart();
                    // 设定邮件内容的类型为 text/plain 或 text/html
                    mbp.setContent(content, "text/html;charset=UTF-8");
                    Multipart mp = new MimeMultipart();
                    mp.addBodyPart(mbp);
                    message.setContent(mp);
                    break;
                case TEXT:
                    //发送文本邮件
                    message.setText(content);
                    break;
            }
            message.setSentDate(new Date());
            //发送邮件,还有另外一种写法
            /*Transport transport = ssn.getTransport("smtp");
            transport.connect(mailInfo.getHostName(), mailInfo.getUserName(), mailInfo.getPassword());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();*/
            Transport.send(message);
            logger.info("mail send successfully from " + mailInfo.getUserName() + " to " + to + " and cc to " + cc);
        } catch (Exception e) {
            result = false;
            synchronized (exceptionCount) {
                if (exceptionCount <= 0) {
                    exceptionCount = 5;
                } else {
                    exceptionCount--;
                    if (send(subject, type, content, to, cc, bcc)) {
                        result = true;
                        exceptionCount = 5;
                    }
                    logger.info("mail send failure ,from " + mailInfo.getUserName() + " to " + to);
                }
            }
            e.printStackTrace();
        }

        return result;
    }

    public boolean test() {
        boolean r = true;
        try {
            logger.info(1 / 0);
        } catch (Exception e) {
            r = false;
            e.printStackTrace();
        }
        return r;
    }

    public static void main(String[] args) {
        MailInfo info;
        String hostName = "mail.sino****.com.cn";
        info = new MailInfo(hostName, "ds1@mail.com.cn", "pwd1");
        mailFromList.add(info);
        info = new MailInfo(hostName, "ds@mail.com.cn", "pwd");
        mailFromList.add(info);


        boolean r = MailUtil.send("test", MailInfo.MailType.HTML, "<div style=\"color:red\">from new mail test</div>", "8****@qq.com", "", "");
        logger.info(r);
    }
}

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值