Skip to content

Commit

Permalink
#338: Return Nullable AsyncResponse from mailer.sendMail(singleArgume…
Browse files Browse the repository at this point in the history
…nt), as async can now be configured through the mailerBuilder as well
  • Loading branch information
bbottema committed Dec 26, 2021
1 parent 3218a81 commit 7195778
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ public interface Mailer {
/**
* Delegates to {@link #sendMail(Email, boolean)}, with <code>async = false</code>. This method returns only when the email has been processed by
* the target SMTP server.
* @return AsyncResponse if the email was configured to be sent asynchronously.
*/
void sendMail(Email email);
@Nullable AsyncResponse sendMail(Email email);

/**
* Processes an {@link Email} instance into a completely configured {@link Message}.
Expand All @@ -85,6 +86,7 @@ public interface Mailer {
* @see #validate(Email)
*/
@Nullable
// FIXME replace with Optional when Java 8?
AsyncResponse sendMail(Email email, @SuppressWarnings("SameParameterValue") boolean async);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public static Session createMailSession(@NotNull final ServerConfig serverConfig
if (serverConfig.getUsername() != null) {
props.put(transportStrategy.propertyNameUsername(), serverConfig.getUsername());
}
// https://www.tutorialspoint.com/javamail_api/javamail_api_smtp_servers.htm
// https://archive.ph/VkrwH (https://www.tutorialspoint.com/javamail_api/javamail_api_smtp_servers.htm)
if (serverConfig.getCustomSSLFactoryInstance() != null) {
props.put("mail.smtp.ssl.socketFactory", serverConfig.getCustomSSLFactoryInstance());
} else if (serverConfig.getCustomSSLFactoryClass() != null) {
Expand Down Expand Up @@ -312,8 +312,9 @@ public synchronized AsyncResponse testConnection(boolean async) {
* @see Mailer#sendMail(Email)
*/
@Override
public final void sendMail(final Email email) {
sendMail(email, getOperationalConfig().isAsync());
@Nullable
public final AsyncResponse sendMail(final Email email) {
return sendMail(email, getOperationalConfig().isAsync());
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package demo;

import org.simplejavamail.api.mailer.AsyncResponse;
import org.simplejavamail.api.mailer.Mailer;
import org.simplejavamail.email.EmailBuilder;

import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Demonstration program for the Simple Java Mail framework. Just fill your gmail, password and press GO.
*/
Expand All @@ -27,7 +30,7 @@ public static void main(final String[] args) throws IOException {
}

private static void testSimplePlainText(Mailer mailerTLS) {
mailerTLS.sendMail(EmailBuilder.startingBlank()
final AsyncResponse result = mailerTLS.sendMail(EmailBuilder.startingBlank()
.to(YOUR_GMAIL_ADDRESS)
.from("Simple Java Mail demo", "[email protected]")
.withSubject("Demo email - simple (using plain text)")
Expand All @@ -39,6 +42,8 @@ private static void testSimplePlainText(Mailer mailerTLS) {
"- plain text (root)")
.clearHTMLText()
.buildEmail());

assertThat(result).isNull();
}

private static void testSimpleHTMLText(Mailer mailerTLS) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -26,8 +27,11 @@ public void setup() {

@Test
public void emailSentSuccesfullyShouldInvokeOnSuccessHandler() throws Exception {
AsyncResponse asyncResponse = sendAsyncMail(true);

emailSentSuccesfullyShouldInvokeOnSuccessHandler(sendAsyncMailUsingMailerAPI(true));
emailSentSuccesfullyShouldInvokeOnSuccessHandler(sendAsyncMailUsingMailerBuilderAPI(true));
}

private void emailSentSuccesfullyShouldInvokeOnSuccessHandler(AsyncResponse asyncResponse) throws InterruptedException, ExecutionException {
// set handlers, then wait for result
final AtomicReference<Boolean> successHandlerInvoked = new AtomicReference<>(false);
final AtomicReference<Boolean> exceptionHandlerInvoked = new AtomicReference<>(false);
Expand All @@ -44,15 +48,18 @@ public void accept(final Exception e) {
}
});
asyncResponse.getFuture().get();

assertThat(successHandlerInvoked).hasValue(true);
assertThat(exceptionHandlerInvoked).hasValue(false);
}

@Test
public void emailSentSuccesfullyShouldInvokeOnSuccessHandlerAfterDelay() throws Exception {
AsyncResponse asyncResponse = sendAsyncMail(true);

emailSentSuccesfullyShouldInvokeOnSuccessHandlerAfterDelay(sendAsyncMailUsingMailerAPI(true));
emailSentSuccesfullyShouldInvokeOnSuccessHandlerAfterDelay(sendAsyncMailUsingMailerBuilderAPI(true));
}

private void emailSentSuccesfullyShouldInvokeOnSuccessHandlerAfterDelay(AsyncResponse asyncResponse) throws InterruptedException, ExecutionException {
// wait for result, then set handlers
asyncResponse.getFuture().get();
final AtomicReference<Boolean> successHandlerInvoked = new AtomicReference<>(false);
Expand All @@ -69,15 +76,18 @@ public void accept(final Exception e) {
exceptionHandlerInvoked.set(true);
}
});

assertThat(successHandlerInvoked).hasValue(true);
assertThat(exceptionHandlerInvoked).hasValue(false);
}

@Test
public void emailSentSuccesfullyShouldInvokeOnExceptionHandler() throws Exception {
AsyncResponse asyncResponse = sendAsyncMail(false);

public void emailSentSuccesfullyShouldInvokeOnExceptionHandler() {
emailSentSuccesfullyShouldInvokeOnExceptionHandler(sendAsyncMailUsingMailerAPI(false));
emailSentSuccesfullyShouldInvokeOnExceptionHandler(sendAsyncMailUsingMailerBuilderAPI(false));
}

private void emailSentSuccesfullyShouldInvokeOnExceptionHandler(AsyncResponse asyncResponse) {
// set handlers, then wait for result
final AtomicReference<Boolean> successHandlerInvoked = new AtomicReference<>(false);
final AtomicReference<Boolean> exceptionHandlerInvoked = new AtomicReference<>(false);
Expand All @@ -93,20 +103,20 @@ public void accept(final Exception e) {
exceptionHandlerInvoked.set(true);
}
});

try {
asyncResponse.getFuture().get();
} catch (Exception e) {
// good
}

assertThat(successHandlerInvoked).hasValue(false);
assertThat(exceptionHandlerInvoked).hasValue(true);
}

@Test
public void emailSentSuccesfullyShouldInvokeOnExceptionHandlerAfterDelay() throws Exception {
AsyncResponse asyncResponse = sendAsyncMail(false);
AsyncResponse asyncResponse = sendAsyncMailUsingMailerAPI(false);

// wait for result, then set handlers
try {
Expand All @@ -132,9 +142,9 @@ public void accept(final Exception e) {
assertThat(successHandlerInvoked).hasValue(false);
assertThat(exceptionHandlerInvoked).hasValue(true);
}

@Nullable
private AsyncResponse sendAsyncMail(boolean sendSuccesfully) {
private AsyncResponse sendAsyncMailUsingMailerAPI(boolean sendSuccesfully) {
final boolean async = true;
return MailerBuilder
.withSMTPServer("localhost", 0)
Expand All @@ -145,6 +155,19 @@ private AsyncResponse sendAsyncMail(boolean sendSuccesfully) {
.withPlainText("")
.buildEmail(), async);
}

@Nullable
private AsyncResponse sendAsyncMailUsingMailerBuilderAPI(boolean sendSuccesfully) {
return MailerBuilder
.withSMTPServer("localhost", 0)
.withCustomMailer(new MySimulatingMailer(sendSuccesfully))
.async()
.buildMailer().sendMail(EmailBuilder.startingBlank()
.to("[email protected]")
.from("Simple Java Mail demo", "[email protected]")
.withPlainText("")
.buildEmail());
}

private static class MySimulatingMailer implements CustomMailer {
final boolean shouldSendSuccesfully;
Expand Down

0 comments on commit 7195778

Please sign in to comment.