6

現在、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();

これは非常に読みやすいですが、大量のメッセージを処理すると遅くなります。これは、メッセージごとに再接続するオーバーヘッドだと思います。そのため、次のコードでプロファイリングしたところ、トランスポートを再利用すると約 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);

    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());

Commons Email で複数の電子メール送信に SMTP 接続を再利用する方法があるかどうか疑問に思っていましたか? 私は Commons Email API の方が気に入っていますが、パフォーマンスはちょっと痛いです。

ありがとう、身代金

4

2 に答える 2

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("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());
于 2011-07-14T21:09:23.350 に答える
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

ここで続行する方法がわからない...

于 2012-01-02T12:12:43.827 に答える