如何在一个会话中发送多封电子邮件?
我想要向不同的收件人发送数千封不同的电子邮件,并且想要打开与我的 SMTP 的连接并保留它。我希望这比重新打开 ervy 邮件的连接更快。我想使用 Apache Commons Email,但如果需要的话可以回退到 Java Mail API。
现在我正在这样做,每次打开连接都会关闭连接:
HtmlEmail email = new HtmlEmail();
email.setHostName(server.getHostName());
email.setSmtpPort(server.getPort());
email.setAuthenticator(new DefaultAuthenticator(server.getUsername(), server.getPassword()));
email.setTLS(true);
email.setFrom("[email protected]");
email.addTo(to);
email.setSubject(subject);
email.setHtmlMsg(htmlMsg);
email.send();
I want to send thousands of different emails to different recipients and would like to open the connection to my SMTP and hold it. I hope this is faster then reopen the connection for ervy mail. I would like to use Apache Commons Email for that, but could fall back to the Java Mail API if necessary.
Right now I'am doing this, what opens a closes the connection every time:
HtmlEmail email = new HtmlEmail();
email.setHostName(server.getHostName());
email.setSmtpPort(server.getPort());
email.setAuthenticator(new DefaultAuthenticator(server.getUsername(), server.getPassword()));
email.setTLS(true);
email.setFrom("[email protected]");
email.addTo(to);
email.setSubject(subject);
email.setHtmlMsg(htmlMsg);
email.send();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我的性能测试课。使用一个连接发送邮件的速度比每次重新打开连接的速度快 4 倍(当您使用公共邮件时会发生什么)。通过使用多线程可以进一步提高性能。
Here is my performance test class. Sending the mails using one connection is 4 times faster then reopen the connection every time (what happens when you use commons mail). The performance can be pushed further by using multiple threads.
您可以使用之前的代码,但添加以下代码来获取底层会话
您可以通过以下方式添加额外的 java 邮件属性
You can use your earlier code but add the following to get the underlying Session
You can add extra java mail properties by
看看 http://java .sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html。有一个示例显示如何发送电子邮件。在调用 Transport 上的 close() 之前,您应该能够发送更多内容。
Have a look at http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html. There is an example showing how to send an email. You should be able to send more before calling close() on the Transport.