How to send multiple emails in one session?

这一生的挚爱 提交于 2019-11-30 19:26:02

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

You can use your earlier code but add the following to get the underlying Session

email.getMailSession();

You can add extra java mail properties by

email.getMailSession().getProperties().put(<key>, <value>);

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.

no need xtra code at all, just put your all email recipients and separate with comma.

MimeMessage pesan = new MimeMessage(session); pesan.setFrom(new InternetAddress("email_from@host.com")); pesan.setRecipients(Message.RecipientType.TO, InternetAddress.parseHeader("first_email@host.com,second_email@host.com,dst_email@host.com",false));

and do the same thing for Message.RecipientType.CC and Message.RecipientType.BCC if there is more than 1 email recipients hope its help :)..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!