我正在尝试使用包装 javax.mail (JavaMail 1.5.0) 的类发送电子邮件。它使用 smtp.gmail.com 发送并且它可以工作,但是效果太好了,因为当我向多个收件人发送电子邮件时,每封电子邮件都会发送(TO + CC)次,所以如果我向 3 个收件人发送电子邮件,我会得到一个总数9 封电子邮件(每封重复 3 次)。
这不好...设置会话调试显示电子邮件已正确发送 1 次,收件人正确。我在jre6u45上。
问题是什么?有没有人有任何提示?我做了一个我没有看到的愚蠢错误吗?
这是我的代码:
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
public class Mailer
{
public static boolean sendMail(
final String username,
final String password,
final String from,
final String _tos,
final String _ccs,
final String _bccs,
final String subject,
final String text,
final File[] attachments)
{
Properties p = null;
Session s = null;
boolean debug = true;
boolean res = false;
boolean isSecured = false;
boolean isSupported = true;
String host = null;
final String charset = "UTF-8";
String fromProvider = from.split("@")[1];
if(fromProvider.compareTo("gmail.com") == 0)
{
isSecured = true;
host = "smtp.gmail.com";
p = System.getProperties();
p.put("mail.smtp.host", host);
p.put("mail.smtps.auth", "true");
p.put("mail.smtp.port", "465");
p.put("mail.smtp.starttls.enable", "true");
p.put("mail.smtp.socketFactory.port", "465");
p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
s = Session.getInstance(p, null);
}
else {isSupported = false;}
if(isSupported)
{
s.setDebug(debug);
try
{
// init
MimeMessage email = new MimeMessage(s);
Multipart mp = new MimeMultipart();
InternetAddress[] tos = {};
InternetAddress[] ccs = {};
InternetAddress[] bccs = {};
// common
if(_tos != null) {tos = InternetAddress.parse(_tos);}
if(_ccs != null) {ccs = InternetAddress.parse(_ccs);}
if(_bccs != null) {bccs = InternetAddress.parse(_bccs);}
email.addRecipients(RecipientType.TO, tos);
email.addRecipients(RecipientType.CC, ccs);
email.addRecipients(RecipientType.BCC, bccs);
email.setSubject (subject, charset);
email.setSentDate (Calendar.getInstance().getTime());
// text part
MimeBodyPart mbpText = new MimeBodyPart();
mbpText.setText(text, charset, "html");
mp.addBodyPart(mbpText);
// attachments
if(attachments != null && attachments.length > 0)
{
for(int i=0; i<attachments.length; i++)
{
MimeBodyPart mbpAttachment = new MimeBodyPart();
mbpAttachment.attachFile(attachments[i]);
mp.addBodyPart(mbpAttachment);
}
}
// build elements
email.setContent(mp);
email.saveChanges();
Address[] addresses = email.getAllRecipients();
// send
Transport.send(email, addresses, username, password);
res = true;
}
catch(MessagingException ex) {ex.printStackTrace();}
catch(IOException ex) {ex.printStackTrace();}
}
return res;
}
}