Skip to content

Commit

Permalink
#64: added support for flagged mode that doesn't send emails, but jus…
Browse files Browse the repository at this point in the history
…t logs it
  • Loading branch information
bbottema committed Feb 26, 2017
1 parent fc2b14b commit 025dcef
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 21 deletions.
16 changes: 16 additions & 0 deletions src/main/java/org/simplejavamail/mailer/Mailer.java
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,22 @@ public void setDebug(final boolean debug) {
mailSender.setDebug(debug);
}

/**
* Sets the transport mode for this mail sender to logging only, which means no mail will be actually sent out.
*
* @param transportModeLoggingOnly Flag to indicate logging mode yes/no.
*/
public synchronized void setTransportModeLoggingOnly(boolean transportModeLoggingOnly) {
mailSender.setTransportModeLoggingOnly(transportModeLoggingOnly);
}

/**
* @return Whether this Mailer is set to only log or also actually send emails through an SMTP server (which is the default).
*/
public boolean isTransportModeLoggingOnly() {
return mailSender.isTransportModeLoggingOnly();
}

/**
* Configures the current session to trust all hosts and don't validate any SSL keys. The property "mail.smtp.ssl.trust" is set to "*".
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@

import org.simplejavamail.MailException;
import org.simplejavamail.email.Email;
import org.simplejavamail.util.ConfigLoader;
import org.simplejavamail.util.ConfigLoader.Property;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.TransportStrategy;
import org.simplejavamail.mailer.internal.socks.AuthenticatingSocks5Bridge;
import org.simplejavamail.mailer.internal.socks.socks5server.AnonymousSocks5Server;
import org.simplejavamail.util.ConfigLoader;
import org.simplejavamail.util.ConfigLoader.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
Expand Down Expand Up @@ -71,13 +73,19 @@ public class MailSender {

private int threadPoolSize;

/**
* Determines whether at the very last moment an email is sent out using JavaMail's native API or whether the email is simply only logged.
*/
private boolean transportModeLoggingOnly;

/**
* @see #configureSessionWithProxy(ProxyConfig, Session, TransportStrategy)
*/
public MailSender(final Session session, final ProxyConfig proxyConfig, final TransportStrategy transportStrategy) {
this.session = session;
this.proxyServer = configureSessionWithProxy(proxyConfig, session, transportStrategy);
this.threadPoolSize = ConfigLoader.valueOrProperty(null, Property.DEFAULT_POOL_SIZE, DEFAULT_POOL_SIZE);
this.transportModeLoggingOnly = ConfigLoader.valueOrProperty(null, Property.TRANSPORT_MODE_LOGGING_ONLY, false);
}

/**
Expand Down Expand Up @@ -186,13 +194,23 @@ private void sendMailClosure(final Session session, final Email email) {
proxyServer.start();
}
}
try {
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
} finally {
LOGGER.trace("closing transport");
//noinspection ThrowFromFinallyBlock
transport.close();

if (!transportModeLoggingOnly) {
LOGGER.trace("\t\nEmail: {}", email);
LOGGER.trace("\t\nMimeMessage: {}\n", readMimeMessageToString(message));

try {
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
} finally {
LOGGER.trace("closing transport");
//noinspection ThrowFromFinallyBlock
transport.close();
}
} else {
LOGGER.info("TRANSPORT_MODE_LOGGING_ONLY: skipping actual sending...");
LOGGER.info("\n\nEmail: {}\n", email);
LOGGER.info("\n\nMimeMessage: {}\n", readMimeMessageToString(message));
}
} finally {
checkShutDownProxyBridge();
Expand All @@ -204,6 +222,16 @@ private void sendMailClosure(final Session session, final Email email) {
}
}

private String readMimeMessageToString(MimeMessage message) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
message.writeTo(os);
return os.toString("UTF-8");
} catch (IOException | MessagingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}

/**
* We need to keep a count of running threads only if we need to shutdown the proxy bridging server at the end in async mode.
* <p>
Expand Down Expand Up @@ -297,4 +325,17 @@ public synchronized void setThreadPoolSize(int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}

}
/**
* Sets the transport mode for this mail sender to logging only, which means no mail will be actually sent out.
*/
public synchronized void setTransportModeLoggingOnly(boolean transportModeLoggingOnly) {
this.transportModeLoggingOnly = transportModeLoggingOnly;
}

/**
* @return {@link #transportModeLoggingOnly}
*/
public boolean isTransportModeLoggingOnly() {
return transportModeLoggingOnly;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public Mailer loadGlobalConfigAndCreateDefaultMailer(
@Value("${simplejavamail.defaults.cc.address:#{null}}") String defaultCcAddress,
@Value("${simplejavamail.defaults.bcc.name:#{null}}") String defaultBccName,
@Value("${simplejavamail.defaults.bcc.address:#{null}}") String defaultBccAddress,
@Value("${simplejavamail.defaults.poolsize:#{null}}") String defaultPoolsize) {
@Value("${simplejavamail.defaults.poolsize:#{null}}") String defaultPoolsize,
@Value("${simplejavamail.transport.mode.logging.only:#{null}}") String defaultTransportModeLoggingOnly) {
Properties emailProperties = new Properties();
setNullableProperty(emailProperties, Property.JAVAXMAIL_DEBUG.key(), javaxmailDebug);
setNullableProperty(emailProperties, Property.TRANSPORT_STRATEGY.key(), transportstrategy);
Expand All @@ -63,6 +64,7 @@ public Mailer loadGlobalConfigAndCreateDefaultMailer(
setNullableProperty(emailProperties, Property.DEFAULT_BCC_NAME.key(), defaultBccName);
setNullableProperty(emailProperties, Property.DEFAULT_BCC_ADDRESS.key(), defaultBccAddress);
setNullableProperty(emailProperties, Property.DEFAULT_POOL_SIZE.key(), defaultPoolsize);
setNullableProperty(emailProperties, Property.TRANSPORT_MODE_LOGGING_ONLY.key(), defaultTransportModeLoggingOnly);

ConfigLoader.loadProperties(emailProperties, true);

Expand Down
9 changes: 7 additions & 2 deletions src/main/java/org/simplejavamail/util/ConfigLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
* <li>simplejavamail.defaults.cc.address</li>
* <li>simplejavamail.defaults.bcc.name</li>
* <li>simplejavamail.defaults.bcc.address</li>
* <li>simplejavamail.defaults.poolsize
* <li>simplejavamail.defaults.poolsize</li>
* <li>simplejavamail.transport.mode.logging.only</li>
* </ul></pre>
*/
public final class ConfigLoader {
Expand Down Expand Up @@ -92,7 +93,8 @@ public enum Property {
DEFAULT_CC_ADDRESS("simplejavamail.defaults.cc.address"),
DEFAULT_BCC_NAME("simplejavamail.defaults.bcc.name"),
DEFAULT_BCC_ADDRESS("simplejavamail.defaults.bcc.address"),
DEFAULT_POOL_SIZE("simplejavamail.defaults.poolsize");
DEFAULT_POOL_SIZE("simplejavamail.defaults.poolsize"),
TRANSPORT_MODE_LOGGING_ONLY("simplejavamail.transport.mode.logging.only");

private final String key;

Expand All @@ -113,6 +115,9 @@ public static <T> T valueOrProperty(final T value, final Property property) {
}

/**
* Returns the given value if not null and not empty, otherwise tries to resolve the given property and if still not found resot to the default value if
* provided.
* <p>
* Null or blank values are never allowed, so they are always ignored.
*
* @return The value if not null or else the value from config file if provided or else <code>defaultValue</code>.
Expand Down
21 changes: 17 additions & 4 deletions src/test/java/demo/MailTestApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,14 @@ public class MailTestApp {
private static final ServerConfig serverConfigTLS = new ServerConfig("smtp.gmail.com", 587, YOUR_GMAIL_ADDRESS, YOUR_GMAIL_PASSWORD);
private static final ServerConfig serverConfigSSL = new ServerConfig("smtp.gmail.com", 465, YOUR_GMAIL_ADDRESS, YOUR_GMAIL_PASSWORD);

/**
* If you just want to see what email is being sent, just set this to true. It won't actually connect to an SMTP server then.
*/
private static final boolean LOGGING_MODE = false;

public static void main(final String[] args)
throws Exception {
// make Simple Java Mail ignore the properties file completely: that's there for the junit tests, not this demo.
ConfigLoaderTestHelper.clearConfigProperties();

final Email emailNormal = new Email();
Expand All @@ -58,10 +64,17 @@ public static void main(final String[] args)
sendMail(emailFromMimeMessage); // should produce the exact same result as emailNormal!
}

private static void sendMail(final Email email) {
private static void sendMail(final Email email)
throws ClassNotFoundException {
// ProxyConfig proxyconfig = new ProxyConfig("localhost", 1030);
new Mailer(serverConfigSMTP, TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer(serverConfigTLS, TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer(serverConfigSSL, TransportStrategy.SMTP_SSL).sendMail(email);
sendMail(serverConfigSMTP, TransportStrategy.SMTP_TLS, email);
sendMail(serverConfigTLS, TransportStrategy.SMTP_TLS, email);
sendMail(serverConfigSSL, TransportStrategy.SMTP_SSL, email);
}

private static void sendMail(ServerConfig serverConfigSMTP, TransportStrategy smtpTls, Email email) {
Mailer mailer = new Mailer(serverConfigSMTP, smtpTls);
mailer.setTransportModeLoggingOnly(LOGGING_MODE);
mailer.sendMail(email);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,4 @@ public void trustHosts(){
mailSender.trustHosts("a", "b", "c");
assertThat(session.getProperties().getProperty("mail.smtp.ssl.trust")).isEqualTo("a,b,c");
}

}
5 changes: 3 additions & 2 deletions src/test/resources/ignore.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ simplejavamail.smtp.port=moo
simplejavamail.smtp.username=moo
simplejavamail.smtp.password=moo
simplejavamail.proxy.host=moo
PROXY_PORT("simplejavamail.proxy.port=moo
simplejavamail.proxy.port=moo
simplejavamail.proxy.username=moo
simplejavamail.proxy.password=moo
simplejavamail.proxy.socks5bridge.port=moo
Expand All @@ -19,4 +19,5 @@ simplejavamail.defaults.to.address=moo
simplejavamail.defaults.cc.name=moo
simplejavamail.defaults.cc.address=moo
simplejavamail.defaults.bcc.name=moo
simplejavamail.defaults.bcc.address=moo
simplejavamail.defaults.bcc.address=moo
simplejavamail.transport.mode.logging.only=moo
3 changes: 2 additions & 1 deletion src/test/resources/simplejavamail.properties
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ simplejavamail.defaults.to.address=to@default.com
simplejavamail.defaults.cc.name=CC Default
simplejavamail.defaults.cc.address=cc@default.com
simplejavamail.defaults.bcc.name=BCC Default
simplejavamail.defaults.bcc.address=bcc@default.com
simplejavamail.defaults.bcc.address=bcc@default.com
simplejavamail.transport.mode.logging.only=false

0 comments on commit 025dcef

Please sign in to comment.