mail

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;


import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


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


/**
 * @author Andypan
 * @date 2017年8月18日下午2:34:33
 */
public class MailUtil
{
protected static Log logger = LogFactory.getLog("com.chinasoft.util.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.setProperty("mail.transport.protocol", "smtp");
// props.put("mail.smtp.port", "25");
// 身份验证,一般邮件服务器都需要身份验证
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
Session ssn = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailInfo.getUserName(), mailInfo.getPassword());
}


});
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());
message.saveChanges();
// 发送邮件,还有另外一种写法
/*
* 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 = "smtp.163.com";
info = new MailInfo(hostName, "177****@chinasoftinc.com", "****iao");
mailFromList.add(info);



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


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;
}


@Override
public String toString() {
return "MailInfo [hostName=" + hostName + ", userName=" + userName + ", count=" + count + "]";
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值