2011-07-14 33 views
6

目前我使用Commons Email发送电子邮件,但是我一直无法找到共享发送的电子邮件之间smtp连接的方法。我有一个像下面的代码:Apache Commons电子邮件和重复使用SMTP连接

Email email = new SimpleEmail(); 
    email.setFrom("[email protected]"); 
    email.addTo("[email protected]"); 
    email.setSubject("Hello Example"); 
    email.setMsg("Hello Example"); 
    email.setSmtpPort(25); 
    email.setHostName("localhost"); 
    email.send(); 

这是非常具有可读性,但速度很慢,当我做大量的消息,我相信这是重新连接每条消息的开销。所以我使用下面的代码对它进行了分析,发现使用重复使用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("[email protected]")); 
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); 
    message.setSubject("Hello Example"); 
    message.setContent("Hello Example", "text/html; charset=ISO-8859-1"); 

    transport.sendMessage(message, message.getAllRecipients()); 

所以我想知道是否有一种方法可以使Commons Email重用为多个电子邮件发送的SMTP连接?我更喜欢Commons Email API,但表现令人痛苦。

感谢, 赎金

回答

3

我想出了挖掘到公地源本身经过以下解决方案。这应该工作,但也有可能是更好的解决方案,我不知道

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("[email protected]"); 
    email.addTo("[email protected]"); 
    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()); 
1

难道我们没有做到这一点通过getMailSession()从第一封电子邮件获取邮件会话,并把它用setMailSession所有后续消息更容易()?

不是100%确定是什么

请注意,通过用户名和密码(在邮件验证的情况下),将创建一个DefaultAuthenticator一个新的邮件会话。这很容易,但可能会出乎意料。如果使用邮件身份验证,但没有提供用户名和密码,则实现假定您已设置身份验证程序并将使用现有的邮件会话(如预期的那样)。

从javadoc中表示,虽然: -/ http://commons.apache.org/email/api-release/org/apache/commons/mail/Email.html#setMailSession%28javax.mail.Session%29

还看到: https://issues.apache.org/jira/browse/EMAIL-96

不知道如何继续在这里...