Skip to content

reusing jakarta.mail.Transport for multiple without using batch-module #569

Closed

Description

@rw7

I'd like to reuse a SMTP connection (and therefore jakarta.mail.Transport) for sending more that one email. I'd like to have some API that can be used like this:

try(MailerTransport transport = mailer.openTransport())
{
	for(int i = 0; i<5; i++)
	{
		transport.sendMail(EmailBuilder.startingBlank().
				...
				withSubject("mail " + i + "/5"));
	}
}

I can't use batch-module, as it wants to maintain threads and the message queue for me. I have just one thread fetching emails from the database and sending it to smtp blockingly. No need for parallel threads or connections pools. Just one thread reusing the transport for more than one email.

I made this possible with hacking simple-java-mail, but it says: "Providing access to Session instance for emergency fall-back scenario. Please let us know why you need it." So here I am.

Best regards,
Ralf.

Activity

  1. bbottema commented on Jul 4, 2026

    @bbottema
    Owner

    Thank you for reporting your use case even if you hacked it already (and it's been a year 😅). I'm going to look into this, sounds like a useful addition.

  2. added this to the 8.13.0 milestone on Jul 4, 2026
  3. bbottema commented on Jul 4, 2026

    @bbottema
    Owner

    Implementation prepared as a small Java API expansion that keeps Jakarta Mail Transport hidden:

    mailer.sendMailsInSimpleBatch(emails);        // uses the mailer's configured async default
    mailer.sendMailsInSimpleBatch(emails, false); // block this Mailer API call until the simple batch is done
    mailer.sendMailsInSimpleBatch(emails, true);  // return immediately; the whole simple batch runs as one scheduled task

    Important distinction: the simple batch itself is never concurrent or pooled. The async flag only controls the immediate Mailer API call. Whether async is true or false, the emails are still sent sequentially, one by one, over one SMTP connection. So async = true does not mean queued sending, parallel sending, connection pooling, retry-oriented flow control, cluster coordination, or batch-module behavior. It only means Simple Java Mail schedules the whole sequential operation on the configured executor and returns a CompletableFuture immediately.

    This is intentionally positioned as a simple fallback for caller-managed loops where the caller already owns the queue/source and only wants to avoid reconnecting per email. For queued sending, connection pooling, concurrency, cluster coordination, retry-oriented flow control, or high-throughput use cases, the batch-module remains the primary API.

  4. rw7 commented on Jul 7, 2026

    @rw7
    Author

    @bbottema

    Hi Benny!

    Thank you for your effort. Unfortunately it doesn't help me with my problem. My email queue is in the database. And I have to mark each mail as "sent" once it has been sent. Because I have to expect the server to restart at any time, thus forgetting anything that is not in database. And I don't want to send mails twice.

    Maybe I should have provided a better code example:

    try(MailerTransport transport = mailer.openTransport())
    {
    	while(database.hasMorePendingMails())
    	{
    		PersistentMail m = database.nextPendingMail();
    		transport.sendMail(EmailBuilder.startingBlank().
    				...
    				withSubject(m.getSubject));
    
    		database.setPending(m, false);
    	}
    }
    

    Shall I open a new issue for that, now this one has been closed?

    Best regards,
    Ralf.

  5. bbottema commented on Jul 7, 2026

    @bbottema
    Owner

    No need to open a new issue. You're right: the simple sequential batch API still does not cover the database-checkpoint case, because the caller cannot mark each item as sent immediately after that specific SMTP send succeeds and before fetching the next pending mail.

    I reopened this issue and am adjusting the unreleased API toward the caller-managed transport scope from your original example:

    try (MailerTransport transport = mailer.openTransport()) {
        while (database.hasMorePendingMails()) {
            PersistentMail mail = database.nextPendingMail();
            transport.sendMail(mail.toEmail());
            database.setPending(mail, false);
        }
    }

    That keeps Jakarta Mail Transport hidden, does not use the batch-module connection pool, and gives the caller the per-message checkpoint point your DB-backed queue needs.

  6. bbottema commented on Jul 7, 2026

    @bbottema
    Owner

    Added a callback-scoped API for this use case, next to the small sendMailsInSimpleBatch(...) convenience API.

    Usage:

    mailer.withOpenConnection(sender -> {
        while (database.hasMorePendingMails()) {
            PersistentMail mail = database.nextPendingMail();
    
            sender.sendMail(mail.toEmail());
            database.setPending(mail, false);
        }
    });

    Simple Java Mail owns opening and closing the SMTP connection, and the callback owns the loop and checkpointing. The delegate intentionally exposes only sendMail(Email): it does not expose Jakarta Mail Transport, and it does not pretend to be a full Mailer.

    This remains outside the batch module: no queue, no connection pool, no async/concurrency. The connection is closed when the callback returns or throws, and checked exceptions from callback code are propagated.

  7. bbottema commented on Jul 8, 2026

    @bbottema
    Owner

    Released in Simple Java Mail v9.0.0, which is now available from Maven Central:

    https://repo1.maven.org/maven2/org/simplejavamail/simple-java-mail/9.0.0/

    Release notes:
    https://github.com/bbottema/simple-java-mail/releases/tag/9.0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions