Logging sent Mail Messages
cdecker Sep 7, 2010 7:08 PMHi all,
I want to be able to intercept and store mail messages that are sent through my web application for later reference. As I understand it the best way to get the rendered content of the message is to actually replace the Transport in the JavaMail session by a custom class that stores the content and then calls the original Transport, but so far I have been unable to do that:
public class LogMailTransport extends SMTPTransport { public LogMailTransport(Session session, URLName urlname) { super(session, urlname); log.debug("Using log mail smtp transport layer."); System.out.println("Using log mail smtp transport layer."); } @Override public void sendMessage(Message message, Address[] addresses) throws MessagingException, SendFailedException { super.sendMessage(message, addresses); log.debug("Sent message: " + message.getSubject() + "\n type: " + message.getContentType() + "\n mail id: " + mailManager.getMail().getId() + "\n"); } }
And to render the content and actually send it I use the following:
Session javaMailSession = Session.getDefaultInstance(System.getProperties()); // does not work. add this row to $JAVA_HOME/jre/lib/javamail.providers // protocol=smtp; type=transport; class=xyz.util.LogMailTransport; vendor=FGCZ; // (possibly also for smtps/xyz.util.LogMailSSLTransport) Provider p = new Provider(Type.TRANSPORT, "smtp", "xyz.util.LogMailTransport", "FGCZ", "1.0"); javaMailSession.setProvider(p); Provider trans = javaMailSession.getProvider("smtp"); Provider transSSL = javaMailSession.getProvider("smtps"); log.debug("smtp transport: " + trans.getClassName() + "smtp ssl transport: " + transSSL.getClassName()); ret = renderer.render(template);
I actually made sure that it is printing my class but then the sendMessage function of my class is never called.
Any idea as to why? Or is there a simpler solution to my problem?