Creating a email message in Java without a mail session

email, jakarta-mail, java

Solution

Using Apache Commons Email, any of the following code could be added to the sendMail method depending on where you want things set.

    HtmlEmail email = new HtmlEmail();
    //email.setDebug(debugMode);
    email.setBounceAddress("bouce@domain.biz");
    email.setHostName("mySMTPHost");


    email.setFrom("myAddress@mydomain.com");
    email.addTo(emailAddress);
    email.addBcc("bccAddres");

    email.setSubject("Your Subject");
    email.setAuthentication("recipient@snailmail.org", "password");
    email.setSSL(true);
    email.setSmtpPort(465);
    email.setHtmlMsg(html);

public static void sendMail(org.apache.commons.mail.HtmlEmail email)
{       
    email.send();
}

Problem

I would like to create a utility method in my app that accepts an email message as an argument and knows how to send it. This utility method would be responsible for knowing which SMTP server to use what credentials it should use to connect to it. The problem that I'm running into with `javax.mail` is that the `javax.mail.Message` class and the `javax.mail.MimeMessage`class expect a `javax.mail.Session` object as an argument to the constructor. So I can't have a method signature like ``` private static void sendMail(javax.mail.Message); ``` because my client classes won't be able to constuct the Message without all the details that I'm trying to abstract away. They would have to know how to create a Session by connecting to the mail server. Is there a way to create a Message without a session, or alternatively a class that encapsulates an email message that doesn't require a session?

Original source