3

I'm using apache commons smtp library to send email using my gmail account. Everything works ok , however the Message-Id header is sent and I'm looking to remove it(not sent it). Digging the net I found something on oracle documentation: http://www.oracle.com/technetwork/java/faq-135477.html#msgid

class MyMessage extends MimeMessage {
    ...

    protected void updateMessageID() throws MessagingException {
    setHeader("Message-ID", "my-message-id");
    }
    ...
}

However I don't know how to implement this in apache commons.

Here is my code:

Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setSSLOnConnect(true);
email.setFrom("user@gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("foo@bar.com");
email.send();

basically I need something like email.setMimeMessage(...) , but there is not such a method, only email.getMimeMessage()

UPDATE - SOLUTION FOUND

public class MyEmail extends SimpleEmail{

    protected MimeMessage createMimeMessage(Session aSession)
    {
        return new MyMessage(aSession);
    }
}

You simply override createMimeMessage method and make sure it returns you own MimeMessage implementation( in this case MyMessage)

Doua Beri
  • 10,612
  • 18
  • 89
  • 138

2 Answers2

3

Email class has a Factory method to create a customized MimeMessage which can be implemented by a derived class, e.g. to set the message id.

You can extend this method in order to set your message id. The next code creates a htmlEmail message with a customized message-id.

HtmlEmail email = new HtmlEmail()
                    {
                        protected MimeMessage createMimeMessage(Session aSession)
                        {
                            return new MimeMessage(aSession)
                                    {
                                        protected void updateHeaders () throws MessagingException
                                        {                     
                                            super.updateHeaders ();
                                            super.setHeader ("Message-ID", "my-message-id");
                                        }
                                    };
                        }
                    };
Castillo
  • 31
  • 3
2

The likely problem is that 'Email' calls saveChanges() on the underlying MimeMessage to commit the headers, which calls the updateHeaders() method which in turn calls the updateMessageID() which will insert a Message-ID header.

Why don't you try sending your e-mail using the java.mail API only, where you have control over the MimeMessage ? The code is even already available

Community
  • 1
  • 1
Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101