Check for mail server SMTPUTF8 support

Viewed 349

I have a system where (registered) users have the possibility to add their own SMTP server for mail sending. Thus I don't know in advance what server a user might add and whether this one supports SMTPUTF8. Now starting from JavaMail 1.6 support for SMTPUTF8 has been added. After enabling this for some servers the following line is printed to the log:

mail.mime.allowutf8 set but server doesn't advertise SMTPUTF8 support

This is correct for that server, however how can I detect whether a server supports this or not? I see two possibilities:

  1. Somehow detect whether a mail server supports SMTPUTF8 - if that is possible?
  2. Add another parameter to the stmp configuration and then the users decide (which in most cases they don't really know I would guess)

So is there a way to detect whether a server supports SMTPUTF8?

I checked the implementation and the com.sun.mail.SMTPTransport seems to provide such a query possibility.

public boolean supportsExtension(String ext)

So calling

SMTPTransport transport = new SMTPTransport(...);
boolean smtputf8 = transport.supportsExtension("SMTPUTF8");

should work. It is using an EHLO command (defined in rfc1869) when connecting to the server. However in my implementation I just call

...
Transport.send(Message msg);

So I do not directly access SMTPTransport. One should not directly access com.sun packages, right?

1 Answers

Using ESMTP with the EHLO command one can query the smtp server for supported extensions. mail.smtp.ehlo=true; must be enabled.

boolean detectUTF8(String smtpServerHost, int smtpServerPort,  String smtpUserName, String smtpUserAccessToken) {
    
    Transport transport = null;
    try {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props);
        //session.setDebug(true);

        transport = session.getTransport();
        transport.connect(smtpServerHost, smtpServerPort, smtpUserName, smtpUserAccessToken);
            
        if(transport instanceof SMTPTransport || transport instanceof SMTPSSLTransport) {
            return ((SMTPTransport)transport).supportsExtension("SMTPUTF8");
        }
        return false;
    } 
    catch (Exception ex) {
        //Proper loggin & exception handling!!!
        //return false;
    }
    finally {
        if(transport!=null) {
            try {
                transport.close();
            }
            catch (MessagingException e) {
            }
        }
    }
}

It would be nice if the supportsExtension(...) method would make it into the Transport interface so that javax.mail could be used.

Related