我有一个通信应用程序,每个用户创建一个通信并将其发送给多个用户(平均发送给我们 2-30 个用户),每次发送我打开一个新线程并按照以下流程向用户组发送电子邮件(连接邮件服务器>发送>关闭连接)如下:
public class EmailService {
private String emailProtocol = null;
private String emailHostSMTP = null;
private String senderEmail = null;
private String senderUser = null;
private String senderPassword = null;
private String senderDisplayName = null;
private String emailPort = null;
public void initConfig() {
emailProtocol = GeneralServices.getConfig("emailProtocol");
emailHostSMTP = GeneralServices.getConfig("emailHostSMTP");
senderEmail = GeneralServices.getConfig("senderEmail");
senderUser = GeneralServices.getConfig("senderUser");
senderPassword = GeneralServices.getConfig("senderPassword");
senderDisplayName = GeneralServices.getConfig("senderDisplayName");
emailPort = GeneralServices.getConfig("emailPort");
if (StringUtils.isBlank(emailPort))
emailPort = "587";
}
public void setProps(Properties props) {
props.put("mail.transport.protocol", emailProtocol);
props.put("mail.smtp.host", emailHostSMTP);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", emailPort);
if (ConfigurationUtils.isEnableStartTlsInEmail())
props.put("mail.smtp.starttls.enable", "true");
if (ConfigurationUtils.isEnableDebugInEmail())
props.put("mail.debug", "true");
}
public void sendEmail(String toUser, String subject, String emailHtmlBody, String bannerPath) throws Exception {
try {
if (StringUtils.isBlank(toUser)) {
return;
}
List<String> toUsers = new ArrayList<String>(1);
toUsers.add(toUser);
sendEmail(toUsers, null, null, subject, emailHtmlBody, bannerPath);
} catch (Exception e) {
throw e;
}
}
public void sendEmail(String fromEmail, String fromDisplayName, List<String> toList, List<String> ccList,
String subject, String emailBody, String filePhysicalPath, String fileName, String fileContentType)
throws Exception {
Transport transport = null;
try {
initConfig();
MimeMultipart multipart = new MimeMultipart();
Authenticator authenticator = new SMTPAuthenticator();
MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
MimeBodyPart bodyPart = new MimeBodyPart();
String html = "";
Properties props = System.getProperties();
setProps(props);
sslSocketFactory.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
Session session = Session.getInstance(props, authenticator);
// session.setDebug(true);
emailBody = emailBody + "<br/><br/>مرسل بواسطة : " + fromDisplayName;
html = "<html><body style='text-align:right'> " + emailBody + " </body></html>";
bodyPart.setContent(html, "text/html; charset=UTF-8");
multipart.addBodyPart(bodyPart);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail, fromDisplayName));
message.setReplyTo(new Address[] { new InternetAddress(fromEmail) });
if (toList != null && toList.size() > 0) {
for (String to : toList) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
}
} else {
throw new Exception("List of users to send email to is empty");
}
if (ccList != null && ccList.size() > 0) {
for (String cc : ccList) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
}
}
// attach file
BodyPart mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePhysicalPath);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, "utf-8", "B"));
multipart.addBodyPart(mimeBodyPart);
// end of file attach
message.setSubject(subject, "UTF-8");
message.setContent(multipart);
message.setSentDate(new Date());
transport = session.getTransport(emailProtocol);
transport.connect(senderEmail, senderPassword);
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception ex) {
throw ex;
} finally {
if (transport != null)
transport.close();
}
}
public void sendEmail(List<String> toList, List<String> ccList, List<String> bccList, String subject,
String emailHtmlBody, String bannerPath) throws Exception {
if ((toList == null || toList.size() == 0) && (ccList == null || ccList.size() == 0)
&& (bccList == null || bccList.size() == 0)) {
return;
}
Transport transport = null;
try {
initConfig();
MimeMultipart multipart = new MimeMultipart();
Authenticator authenticator = new SMTPAuthenticator();
MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
MimeBodyPart bodyPart = new MimeBodyPart();
String html = "";
Properties props = System.getProperties();
setProps(props);
sslSocketFactory.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
Session session = Session.getInstance(props, authenticator);
html = "<html><body> " + emailHtmlBody + " </body></html>";
bodyPart.setContent(html, "text/html; charset=UTF-8");
multipart.addBodyPart(bodyPart);
// add banner path
bodyPart = new MimeBodyPart();
DataSource ds = new FileDataSource(bannerPath);
bodyPart.setDataHandler(new DataHandler(ds));
bodyPart.setHeader("Content-ID", "<MOAMALAT_LOGO>");
multipart.addBodyPart(bodyPart);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail, senderDisplayName));
message.setReplyTo(new Address[] { new InternetAddress(senderEmail) });
if (toList != null && toList.size() > 0) {
for (String email : toList)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
}
if (ccList != null && ccList.size() > 0) {
for (String email : ccList)
message.addRecipient(Message.RecipientType.CC, new InternetAddress(email));
}
if (bccList != null && bccList.size() > 0) {
for (String email : bccList)
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email));
}
message.setSubject(subject, "UTF-8");
message.setContent(multipart);
message.setSentDate(new Date());
transport = session.getTransport(emailProtocol);
transport.connect(senderEmail, senderPassword);
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception ex) {
throw ex;
} finally {
if (transport != null)
transport.close();
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = senderUser;
String password = senderPassword;
return new PasswordAuthentication(username, password);
}
}
}
有时我会得到错误:
com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit
但在与 Exchange Server 管理员审查后,他说我没有发送超过限制的电子邮件。
有时我也会收到错误:
java.net.SocketException: Connection reset
有时我也会得到:
javax.mail.MessagingException: Can't send command to SMTP host,Caused by: java.net.SocketException: Connection closed by remote host
我读到有些人将传输对象设为静态并仅与交换服务器建立一次连接然后重新使用它,这是否有助于解决问题,连接将打开多长时间?
我还想到了一种解决方案,将电子邮件详细信息保存在数据库表中,并制作一个作业类以定期批量发送电子邮件。
最佳答案
我编辑了您第二次声明的 sendEmail 方法(如下所示)。如果您喜欢,请将相同的技术应用于其他 sendEmail 方法。
作为解决方案,我将 sendMessage 部分抓取到 cc 列表的 for 循环中。因此,对于每个“收件人”电子邮件和每个相应的“抄送”电子邮件,将发送电子邮件。抄送列表的缺失也必须由您评估。代码可能无法编译,但您应该明白这一点。
public void sendEmail(String fromEmail, String fromDisplayName, List<String> toList, List<String> ccList,
String subject, String emailBody, String filePhysicalPath, String fileName, String fileContentType)
throws Exception {
Transport transport = null;
try {
initConfig();
MimeMultipart multipart = new MimeMultipart();
Authenticator authenticator = new SMTPAuthenticator();
MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
MimeBodyPart bodyPart = new MimeBodyPart();
String html = "";
Properties props = System.getProperties();
setProps(props);
sslSocketFactory.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
Session session = Session.getInstance(props, authenticator);
// session.setDebug(true);
emailBody = emailBody + "<br/><br/>مرسل بواسطة : " + fromDisplayName;
html = "<html><body style='text-align:right'> " + emailBody + " </body></html>";
bodyPart.setContent(html, "text/html; charset=UTF-8");
multipart.addBodyPart(bodyPart);
MimeMessage message = new MimeMessage(session);
// attach file
BodyPart mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePhysicalPath);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, "utf-8", "B"));
multipart.addBodyPart(mimeBodyPart);
// end of file attach
message.setSubject(subject, "UTF-8");
message.setContent(multipart);
message.setFrom(new InternetAddress(senderEmail, fromDisplayName));
message.setReplyTo(new Address[] { new InternetAddress(fromEmail) });
transport = session.getTransport(emailProtocol);
transport.connect(senderEmail, senderPassword);
if (toList != null && toList.size() > 0) {
for (String to : toList) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
if (ccList != null && ccList.size() > 0) {
for (String cc : ccList) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
message.setSentDate(new Date());
transport.sendMessage(message, message.getAllRecipients());
}
}
}
} else {
throw new Exception("List of users to send email to is empty");
}
} catch (Exception ex) {
throw ex;
} finally {
if (transport != null)
transport.close();
}
}
关于java - 无法在短时间内发送太多电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466897/
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)
我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub
GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'