Ran*_*ggs 6 java email apache-commons-email
目前我使用Commons Email发送电子邮件,但我找不到在发送的电子邮件之间共享smtp连接的方法.我有以下代码:
Email email = new SimpleEmail();
email.setFrom("example@example.com");
email.addTo("example@example.com");
email.setSubject("Hello Example");
email.setMsg("Hello Example");
email.setSmtpPort(25);
email.setHostName("localhost");
email.send();
Run Code Online (Sandbox Code Playgroud)
这是非常易读的,但是当我执行大量消息时速度很慢,我认为这是重新连接每条消息的开销.因此,我使用以下代码对其进行了分析,并发现使用重新使用Transport会使事情快三倍.
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport("smtp");
transport.connect("localhost", 25, null, null);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("example@example.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("example@example.com"));
message.setSubject("Hello Example");
message.setContent("Hello Example", "text/html; charset=ISO-8859-1");
transport.sendMessage(message, message.getAllRecipients());
Run Code Online (Sandbox Code Playgroud)
所以我想知道是否有办法让Commons Email重用多个电子邮件发送的SMTP连接?我更喜欢Commons Email API,但性能有点痛苦.
谢谢,赎金
在深入研究公共资源本身后,我想出了以下解决方案。这应该可行,但可能有更好的解决方案我不知道
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport("smtp");
transport.connect("localhost", 25, null, null);
Email email = new SimpleEmail();
email.setFrom("example@example.com");
email.addTo("example@example.com");
email.setSubject("Hello Example");
email.setMsg("Hello Example");
email.setHostName("localhost"); // buildMimeMessage call below freaks out without this
// dug into the internals of commons email
// basically send() is buildMimeMessage() + Transport.send(message)
// so rather than using Transport, reuse the one that I already have
email.buildMimeMessage();
Message m = email.getMimeMessage();
transport.sendMessage(m, m.getAllRecipients());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3767 次 |
| 最近记录: |