由于QQ邮箱对于SMTP服务发送邮件做了限制,每分钟发送40封之后会被限制不能再发送,对于这样的限制又需要发送大量邮件的时候的解决方案如下
使用多个邮箱轮换使用进行发送
1、将使用的邮箱存储在一个统一的字符串变量中,将所有可使用的邮箱存储在一个字符串数组中(我的三个邮箱授权码相同,如果授权码不同,则建立一个授权码数组,和邮箱切换的解决方案同理)
全局变量(发邮件使用的邮箱)
private static String FPAMail="freeprogramming@qq.com";
可使用的邮箱数组
private static String FPAMailArray[]={"freeprogramming@qq.com","humorchen@vip.qq.com","3301633914@qq.com"};
2、将建立连接的代码封装到一个函数,将连接对象变为成员变量,全局化,即每次调用同一个变量,而变量的对象可能不相同(会变化)
连接相关对象变为全局变量
private static Properties props;
private static Session mailSession;
private static MimeMessage message;
private static Transport transport;
建立连接的函数
private void init()
{
System.out.println("QQ邮件服务初始化开始:账号"+FPAMail);
Date start=new Date();
try {
// 创建Properties 类用于记录邮箱的一些属性
props = new Properties();
// 表示SMTP发送邮件,必须进行身份验证
props.put("mail.smtp.auth", "true");
//此处填写SMTP服务器
props.put("mail.smtp.host", "smtp.qq.com");
//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587
props.put("mail.smtp.port", "587");
// 此处填写你的账号
props.put("mail.user",FPAMail );
// 此处的密码就是前面说的16位STMP口令
props.put("mail.password", FPAMailPwd);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
mailSession = Session.getInstance(props, authenticator);// 创建邮件消息
message = new MimeMessage(mailSession);
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"),NickName,"utf-8");
message.setFrom(form);
}catch (Exception e)
{
e.printStackTrace();
}
Date end=new Date();
System.out.println("QQ邮件发送会话初始化成功,耗时"+((end.getTime()-start.getTime()))+"毫秒");
}
(不懂这几个对象是干嘛的百度)
3、设置每发送20封邮件切换一次邮箱,封装成函数
函数如下:
private void switchMail()
{
int i=0;
for (;i<FPAMailArray.length;i++)
if (FPAMail.equals(FPAMailArray[i]))
break;
if (i+1==FPAMailArray.length)
i=0;
else
i++;
FPAMail=FPAMailArray[i];
init();
}
4、每次发送邮件的时候做判断(i%20==0)
public void sendToAllMember(String title,String html_content)
{
System.out.println("发送邮件给所有会员");
int i=1;
for (String mail: MemberQQMailData.mails)
{
System.out.println("正在处理第"+(i++)+"个"+"剩余"+(MemberQQMailData.mails.length-i+1)+"个,正在发送给:"+mail);
sendQQMail(title,MailContentGenerator.QQMailNotice(title,html_content),mail);
if (i%20==0)
switchMail();
}
}
(MemberQQMailData.mails是一个字符串数组,存有所有会员的QQ邮箱)
效果图:每到第20封邮件就换一个邮箱进行发送,完美解决QQ邮箱发送限制问题