Fake javax.mail.Session
email, jakarta-mail, java
Solution
For this problem I would use a custom `javax.mail.Transport` which is registered to the SMTP protocol.
First implement the CustomTransport class
import javax.mail.Transport;
import javax.mail.*;
public class CustomTransport extends Transport {
public CustomTransport(Session smtpSession, URLName urlName) {
super(smtpSession, urlName);
}
@Override
public void sendMessage(Message message, Address[] addresses) throws MessagingException {
// Take the message and write it somewhere
// e.g.: a logger or an OutputStream message.writeTo(...);
}
@Override
public void connect() throws MessagingException {}
@Override
public void connect(String host, int port, String username, String password) throws MessagingException {}
@Override
public void connect(String host, String username, String password) throws MessagingException {}
@Override
public void close() {}
}
Afterwards you can use that CustomTransport to create a `javax.mail.Session` which writes your mails to the defined location
public Session getMailSession(){
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.provider.class", CustomTransport.class.getName());
props.put("mail.smtp.provider.vendor", "foo");
props.put("mail.smtp.provider.version", "0.0.0");
return Session.getInstance(props);
}
Problem
I have an application that sends emails. But in my development environment, I don't want the application to send email, rather it should only print the message in log file. There are a fake `javax.mail.Session` implementation that I can do this?