如何在一个会话中发送多个电子邮件? [英] How to send multiple emails in one session?

查看:202
本文介绍了如何在一个会话中发送多个电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数千个不同的电子邮件发送给不同的收件人,并希望打开与我的SMTP的连接并保持它。我希望这是更快的,然后重新打开连接的ervy邮件。我想使用Apache Commons Email,但如果需要,可能会回到Java Mail API。

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("test@example.com");
email.addTo(to);
email.setSubject(subject);
email.setHtmlMsg(htmlMsg);
email.send();


推荐答案

这是我的性能测试类。使用一个连接发送邮件的速度快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.

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", server);
    properties.put("mail.smtp.port", "" + port);

    Session session = Session.getInstance(properties);
    Transport transport = session.getTransport("smtp");

    transport.connect(server, username, password);

    for (int i = 0; i < count; i++) {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        message.setRecipients(Message.RecipientType.TO, address);

        message.setSubject(subject + "JavaMail API");
        message.setSentDate(new Date());

        setHTMLContent(message);
        message.saveChanges();
        transport.sendMessage(message, address);

    }

    transport.close();

这篇关于如何在一个会话中发送多个电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆