我通过spring批处理使用spring邮件smtp发送电子邮件。发送每封邮件至少需要1秒。我们每批工作将发送1000封邮件。由于每封邮件只有1秒的时间,所以发送1000多封邮件似乎要花很多时间。因此,我计划使用多线程来发送一大块(大小=100)工作中的所有电子邮件。我用这种方法成功地发了一点邮件。
只要邮件总数非常小,多线程就可以工作,比如每批40封电子邮件(甚至不包括块的大小)。如果邮件计数超过smtp抛出的计数 java.net.sockettimeoutexception read timed out
. 即使增加超时也不起作用。但是当我不使用多线程发送邮件时,它们工作得非常好。
应用程序属性
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.ehlo=false
spring.mail.properties.mail.smtp.ssl.enable=false
spring.mail.properties.mail.smtp.ssl.checkserveridentity=false
spring.mail.properties.mail.debug=false
spring.mail.properties[mail.smtp.connectiontimeout]=10000
spring.mail.properties[mail.smtp.timeout]=10000
spring.mail.properties[mail.smtp.writetimeout]=10000
spring.mail.properties[mail.mime.charset]=UTF-8
作家
@Autowired
EmailSender emailSender;
ExecutorService executor = Executors.newCachedThreadPool();
Collection<Callable<Map<BBEmailOutreach, Boolean>>> tasks = new ArrayList<>();
items.stream().filter(item -> item != null).forEach(item -> {
tasks.add(new ParallelMail(item, emailSender));
}
try {
futureMailStatus = executor.invokeAll(tasks);
} catch (InterruptedException e) {
e.printStackTrace();
}
电子邮件发送者.java
public class EmailSender {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(EmailInfo emailInfo) {
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
true);
message.setTo(emailInfo.getToEmailAddress().split(","));
message.setFrom(new InternetAddress(emailInfo.getFromEmailAddress()));
message.setSubject(emailInfo.getSubject());
message.setText(emailInfo.getMessage(), true);
if(null != emailInfo.getCc() && emailInfo.getCc().length >1)
{
message.setCc(emailInfo.getCc());
}
if (emailInfo.getAttachmentPath() != null) {
FileSystemResource file = new FileSystemResource(
emailInfo.getAttachmentPath());
message.addAttachment(emailInfo.getAttachmentName(), file);
}
}
};
this.javaMailSender.send(preparator);
}
}
例外
org.springframework.mail.MailSendException: Failed messages: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
请告知如何使用多线程而不出现任何错误。
暂无答案!
目前还没有任何答案,快来回答吧!