下面列出了javax.mail.AuthenticationFailedException#javax.mail.SendFailedException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Show the error list from the e-mail API if there are errors
*
* @param parent
* @param sfe
*/
private void showFailedException(SendFailedException sfe) {
String error = sfe.getMessage() + "\n";
Address[] ia = sfe.getInvalidAddresses();
if (ia != null) {
for (int x = 0; x < ia.length; x++) {
error += "Invalid Address: " + ia[x].toString() + "\n";
}
}
JTextArea ea = new JTextArea(error,6,50);
JScrollPane errorScrollPane = new JScrollPane(ea);
errorScrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
errorScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JOptionPane.showMessageDialog(null,
errorScrollPane,
LangTool.getString("em.titleConfirmation"),
JOptionPane.ERROR_MESSAGE);
}
private MessagingException handleSendFailExceptionOnMxIteration(Mail mail, SendFailedException sfe) throws SendFailedException {
logSendFailedException(sfe);
if (sfe.getValidSentAddresses() != null) {
Address[] validSent = sfe.getValidSentAddresses();
if (validSent.length > 0) {
LOGGER.debug("Mail ({}) sent successfully for {}", mail.getName(), validSent);
}
}
EnhancedMessagingException enhancedMessagingException = new EnhancedMessagingException(sfe);
if (enhancedMessagingException.isServerError()) {
throw sfe;
}
final Address[] validUnsentAddresses = sfe.getValidUnsentAddresses();
if (validUnsentAddresses != null && validUnsentAddresses.length > 0) {
if (configuration.isDebug()) {
LOGGER.debug("Send failed, {} valid addresses remain, continuing with any other servers", (Object) validUnsentAddresses);
}
return sfe;
} else {
// There are no valid addresses left to send, so rethrow
throw sfe;
}
}
@Test
public void handleSenderFailedExceptionShouldReturnPermanentFailureWhenInvalidAndNotValidUnsent() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {};
Address[] invalid = {new InternetAddress(MailAddressFixture.ANY_AT_JAMES.asString())};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
ExecutionResult executionResult = testee.handleSenderFailedException(mail, sfe);
assertThat(executionResult).isEqualTo(ExecutionResult.permanentFailure(sfe));
}
@Test
public void handleSenderFailedExceptionShouldReturnTemporaryFailureWhenValidUnsent() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
Address[] invalid = {};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
ExecutionResult executionResult = testee.handleSenderFailedException(mail, sfe);
assertThat(executionResult).isEqualTo(ExecutionResult.temporaryFailure(sfe));
}
@Test
public void handleSenderFailedExceptionShouldReturnTemporaryFailureWhenInvalidAndValidUnsent() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
Address[] invalid = {new InternetAddress(MailAddressFixture.ANY_AT_JAMES.asString())};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
ExecutionResult executionResult = testee.handleSenderFailedException(mail, sfe);
assertThat(executionResult).isEqualTo(ExecutionResult.temporaryFailure(sfe));
}
@Test
public void handleSenderFailedExceptionShouldSetRecipientToInvalidWhenOnlyInvalid() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {};
Address[] invalid = {new InternetAddress(MailAddressFixture.ANY_AT_JAMES.asString())};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
testee.handleSenderFailedException(mail, sfe);
assertThat(mail.getRecipients()).containsOnly(MailAddressFixture.ANY_AT_JAMES);
}
@Test
public void handleSenderFailedExceptionShouldSetRecipientToValidUnsentWhenOnlyValidUnsent() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
Address[] invalid = {};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
testee.handleSenderFailedException(mail, sfe);
assertThat(mail.getRecipients()).containsOnly(MailAddressFixture.OTHER_AT_JAMES);
}
@Test
public void handleSenderFailedExceptionShouldSetRecipientToValidUnsentWhenValidUnsentAndInvalid() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
Address[] invalid = {new InternetAddress(MailAddressFixture.ANY_AT_JAMES.asString())};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
testee.handleSenderFailedException(mail, sfe);
assertThat(mail.getRecipients()).containsOnly(MailAddressFixture.OTHER_AT_JAMES);
}
@Test
public void handleSenderFailedExceptionShouldBounceInvalidAddressesOnBothInvalidAndValidUnsent() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
Address[] invalid = {new InternetAddress(MailAddressFixture.ANY_AT_JAMES.asString())};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
testee.handleSenderFailedException(mail, sfe);
verify(bouncer).bounce(mail, sfe);
verifyNoMoreInteractions(bouncer);
}
@Test
public void deliverShouldAttemptDeliveryOnBothMXIfStillRecipients() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
Address[] invalid = {};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
UnmodifiableIterator<HostAddress> dnsEntries = ImmutableList.of(
HOST_ADDRESS_1,
HOST_ADDRESS_2).iterator();
when(dnsHelper.retrieveHostAddressIterator(MailAddressFixture.JAMES_APACHE_ORG)).thenReturn(dnsEntries);
when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class)))
.thenThrow(sfe);
ExecutionResult executionResult = testee.deliver(mail);
verify(mailDelivrerToHost, times(2)).tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class));
assertThat(executionResult.getExecutionState()).isEqualTo(ExecutionResult.ExecutionState.TEMPORARY_FAILURE);
}
@Test
public void deliverShouldWorkIfOnlyMX2Valid() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
Address[] validSent = {};
Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
Address[] invalid = {};
SendFailedException sfe = new SendFailedException("Message",
new Exception(),
validSent,
validUnsent,
invalid);
UnmodifiableIterator<HostAddress> dnsEntries = ImmutableList.of(
HOST_ADDRESS_1,
HOST_ADDRESS_2).iterator();
when(dnsHelper.retrieveHostAddressIterator(MailAddressFixture.JAMES_APACHE_ORG)).thenReturn(dnsEntries);
when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), eq(HOST_ADDRESS_1)))
.thenThrow(sfe);
when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), eq(HOST_ADDRESS_2)))
.thenReturn(ExecutionResult.success());
ExecutionResult executionResult = testee.deliver(mail);
verify(mailDelivrerToHost, times(2)).tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class));
assertThat(executionResult.getExecutionState()).isEqualTo(ExecutionResult.ExecutionState.SUCCESS);
}
@Test
public void bounceShouldCustomizeSendFailedExceptionByDefault() throws Exception {
RemoteDeliveryConfiguration configuration = new RemoteDeliveryConfiguration(
DEFAULT_REMOTE_DELIVERY_CONFIG,
mock(DomainList.class));
Bouncer testee = new Bouncer(configuration, mailetContext);
Mail mail = FakeMail.builder().name("name").state(Mail.DEFAULT)
.sender(MailAddressFixture.ANY_AT_JAMES)
.build();
String exceptionMessage = "Error from remote server";
testee.bounce(mail, new MessagingException("Exception message", new SendFailedException(exceptionMessage)));
FakeMailContext.BouncedMail expected = new FakeMailContext.BouncedMail(FakeMailContext.fromMail(mail),
"Hi. This is the James mail server at " + HELLO_NAME + ".\n" +
"I'm afraid I wasn't able to deliver your message to the following addresses.\n" +
"This is a permanent error; I've given up. Sorry it didn't work out. Below\n" +
"I include the list of recipients and the reason why I was unable to deliver\n" +
"your message.\n" +
"\n" +
"Remote mail server told me: " + exceptionMessage + "\n\n",
Optional.empty());
assertThat(mailetContext.getSentMails()).isEmpty();
assertThat(mailetContext.getBouncedMails()).containsOnly(expected);
}
private ExecutionResult doDeliver(Mail mail, Set<InternetAddress> addr, Iterator<HostAddress> targetServers) throws MessagingException {
MessagingException lastError = null;
Set<InternetAddress> targetAddresses = new HashSet<>(addr);
while (targetServers.hasNext()) {
try {
return mailDelivrerToHost.tryDeliveryToHost(mail, targetAddresses, targetServers.next());
} catch (SendFailedException sfe) {
lastError = handleSendFailExceptionOnMxIteration(mail, sfe);
targetAddresses.removeAll(listDeliveredAddresses(sfe));
} catch (MessagingException me) {
lastError = handleMessagingException(mail, me);
if (configuration.isDebug()) {
LOGGER.debug(me.getMessage(), me.getCause());
} else {
LOGGER.info(me.getMessage());
}
}
}
// If we encountered an exception while looping through,
// throw the last MessagingException we caught. We only
// do this if we were unable to send the message to any
// server. If sending eventually succeeded, we exit
// deliver() though the return at the end of the try
// block.
if (lastError != null) {
throw lastError;
}
return ExecutionResult.temporaryFailure();
}
private Collection<InternetAddress> listDeliveredAddresses(SendFailedException sfe) {
return Optional.ofNullable(sfe.getValidSentAddresses())
.map(addresses ->
Arrays.stream(addresses)
.map(InternetAddress.class::cast)
.collect(Guavate.toImmutableList()))
.orElse(ImmutableList.of());
}
@VisibleForTesting
ExecutionResult handleSenderFailedException(Mail mail, SendFailedException sfe) {
logSendFailedException(sfe);
EnhancedMessagingException enhancedMessagingException = new EnhancedMessagingException(sfe);
List<MailAddress> invalidAddresses = AddressesArrayToMailAddressListConverter.getAddressesAsMailAddress(sfe.getInvalidAddresses());
List<MailAddress> validUnsentAddresses = AddressesArrayToMailAddressListConverter.getAddressesAsMailAddress(sfe.getValidUnsentAddresses());
if (configuration.isDebug()) {
LOGGER.debug("Mail {} has initially recipients: {}", mail.getName(), mail.getRecipients());
if (!invalidAddresses.isEmpty()) {
LOGGER.debug("Invalid recipients: {}", invalidAddresses);
}
if (!validUnsentAddresses.isEmpty()) {
LOGGER.debug("Unsent recipients: {}", validUnsentAddresses);
}
}
if (!validUnsentAddresses.isEmpty()) {
if (!invalidAddresses.isEmpty()) {
mail.setRecipients(invalidAddresses);
bouncer.bounce(mail, sfe);
}
mail.setRecipients(validUnsentAddresses);
if (enhancedMessagingException.hasReturnCode()) {
boolean isPermanent = enhancedMessagingException.isServerError();
return logAndReturn(mail, ExecutionResult.onFailure(isPermanent, sfe));
} else {
return logAndReturn(mail, ExecutionResult.temporaryFailure(sfe));
}
}
if (!invalidAddresses.isEmpty()) {
mail.setRecipients(invalidAddresses);
return logAndReturn(mail, ExecutionResult.permanentFailure(sfe));
}
if (enhancedMessagingException.hasReturnCode() || enhancedMessagingException.hasNestedReturnCode()) {
if (enhancedMessagingException.isServerError()) {
return ExecutionResult.permanentFailure(sfe);
}
}
return ExecutionResult.temporaryFailure(sfe);
}
private void logSendFailedException(SendFailedException sfe) {
if (configuration.isDebug()) {
EnhancedMessagingException enhancedMessagingException = new EnhancedMessagingException(sfe);
if (enhancedMessagingException.hasReturnCode()) {
LOGGER.info("SMTP SEND FAILED: Command [{}] RetCode: [{}] Response[{}]", enhancedMessagingException.computeCommand(),
enhancedMessagingException.getReturnCode(), sfe.getMessage());
} else {
LOGGER.info("Send failed", sfe);
}
logLevels(sfe);
}
}
public String explanationText(Mail mail, Exception ex) {
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
out.println("Hi. This is the James mail server at " + resolveMachineName() + ".");
out.println("I'm afraid I wasn't able to deliver your message to the following addresses.");
out.println("This is a permanent error; I've given up. Sorry it didn't work out. Below");
out.println("I include the list of recipients and the reason why I was unable to deliver");
out.println("your message.");
out.println();
for (MailAddress mailAddress : mail.getRecipients()) {
out.println(mailAddress);
}
if (ex instanceof MessagingException) {
if (((MessagingException) ex).getNextException() == null) {
out.println(sanitizeExceptionMessage(ex));
} else {
Exception ex1 = ((MessagingException) ex).getNextException();
if (ex1 instanceof SendFailedException) {
out.println("Remote mail server told me: " + sanitizeExceptionMessage(ex1));
} else if (ex1 instanceof UnknownHostException) {
out.println("Unknown host: " + sanitizeExceptionMessage(ex1));
out.println("This could be a DNS server error, a typo, or a problem with the recipient's mail server.");
} else if (ex1 instanceof ConnectException) {
// Already formatted as "Connection timed out: connect"
out.println(sanitizeExceptionMessage(ex1));
} else if (ex1 instanceof SocketException) {
out.println("Socket exception: " + sanitizeExceptionMessage(ex1));
} else {
out.println(sanitizeExceptionMessage(ex1));
}
}
}
out.println();
return sout.toString();
}
@Test
public void handleSenderFailedExceptionShouldReturnTemporaryFailureByDefault() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
SendFailedException sfe = new SendFailedException();
ExecutionResult executionResult = testee.handleSenderFailedException(mail, sfe);
assertThat(executionResult).isEqualTo(ExecutionResult.temporaryFailure(sfe));
}
@Test
public void handleSenderFailedExceptionShouldReturnTemporaryFailureWhenNotServerException() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
SendFailedException sfe = new SMTPSenderFailedException(new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString()), "Comand", 400, "An temporary error");
ExecutionResult executionResult = testee.handleSenderFailedException(mail, sfe);
assertThat(executionResult).isEqualTo(ExecutionResult.temporaryFailure(sfe));
}
@Test
public void handleSenderFailedExceptionShouldReturnPermanentFailureWhenServerException() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
SendFailedException sfe = new SMTPSenderFailedException(new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString()), "Comand", 505, "An temporary error");
ExecutionResult executionResult = testee.handleSenderFailedException(mail, sfe);
assertThat(executionResult).isEqualTo(ExecutionResult.permanentFailure(sfe));
}
@Test
public void deliverShouldAttemptDeliveryOnlyOnceIfNoMoreValidUnsent() throws Exception {
Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
UnmodifiableIterator<HostAddress> dnsEntries = ImmutableList.of(
HOST_ADDRESS_1,
HOST_ADDRESS_2).iterator();
when(dnsHelper.retrieveHostAddressIterator(MailAddressFixture.JAMES_APACHE_ORG)).thenReturn(dnsEntries);
when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class)))
.thenThrow(new SendFailedException());
ExecutionResult executionResult = testee.deliver(mail);
verify(mailDelivrerToHost, times(1)).tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class));
assertThat(executionResult.getExecutionState()).isEqualTo(ExecutionResult.ExecutionState.TEMPORARY_FAILURE);
}
/**
* handles the sendFailedException
* <p>
* creates a MessageSendStatus which contains a translateable info or error message, and the knowledge if the user can proceed with its action.
*
* @param e
* @throws OLATRuntimeException return MessageSendStatus
*/
private MessageSendStatus handleSendFailedException(final SendFailedException e) {
// get wrapped excpetion
MessageSendStatus messageSendStatus = null;
final MessagingException me = (MessagingException) e.getNextException();
if (me instanceof AuthenticationFailedException) {
messageSendStatus = createAuthenticationFailedMessageSendStatus();
return messageSendStatus;
}
final String message = me.getMessage();
if (message.startsWith("553")) {
messageSendStatus = createInvalidDomainMessageSendStatus();
} else if (message.startsWith("Invalid Addresses")) {
messageSendStatus = createInvalidAddressesMessageSendStatus(e.getInvalidAddresses());
} else if (message.startsWith("503 5.0.0")) {
messageSendStatus = createNoRecipientMessageSendStatus();
} else if (message.startsWith("Unknown SMTP host")) {
messageSendStatus = createUnknownSMTPHost();
} else if (message.startsWith("Could not connect to SMTP host")) {
messageSendStatus = createCouldNotConnectToSmtpHostMessageSendStatus();
} else {
List<ContactList> emailToContactLists = getTheToContactLists();
String exceptionMessage = "";
for (ContactList contactList : emailToContactLists) {
exceptionMessage += contactList.toString();
}
throw new OLATRuntimeException(ContactUIModel.class, exceptionMessage, me);
}
return messageSendStatus;
}
private boolean sendEmail(String from, String mailto, String subject, String body) throws AddressException, SendFailedException, MessagingException {
if (webappAndMailHelper.isEmailFunctionalityDisabled()) return false;
InternetAddress mailFromAddress = new InternetAddress(from);
InternetAddress mailToAddress[] = InternetAddress.parse(mailto);
MailerResult result = new MailerResult();
MimeMessage msg = webappAndMailHelper.createMessage(mailFromAddress, mailToAddress, null, null, body + footer, subject, null, result);
webappAndMailHelper.send(msg, result);
//TODO:discuss why is the MailerResult not used here?
return true;
}
@Test
public void testSendWithoutException() {
//setup
ExceptionHandlingMailSendingTemplate doSendWithoutException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
return true;
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithoutException.send();
//verify
assertEquals(MessageSendStatusCode.SUCCESSFULL_SENT_EMAILS, sendStatus.getStatusCode());
assertTrue(sendStatus.getStatusCode().isSuccessfullSentMails());
assertFalse(sendStatus.isSeverityError());
assertFalse(sendStatus.isSeverityWarn());
assertTrue(sendStatus.canProceedWithWorkflow());
}
@Test
public void shouldFailWithAddressExcpetion(){
//setup
ExceptionHandlingMailSendingTemplate doSendWithAddressException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
throw new AddressException();
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithAddressException.send();
//verify
assertEquals(MessageSendStatusCode.SENDER_OR_RECIPIENTS_NOK_553, sendStatus.getStatusCode());
verifyStatusCodeIndicateAddressExceptionOnly(sendStatus);
verifySendStatusIsWarn(sendStatus);
assertFalse(sendStatus.canProceedWithWorkflow());
}
@Test
public void shouldFailWithSendFailedExceptionWithDomainErrorCode553(){
//setup
ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
MessagingException firstInnerException = new SendFailedException("553 some domain error message from the mailsystem");
throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException);
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithSendFailedException.send();
//verify
assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_INVALID_DOMAIN_NAME_553, sendStatus.getStatusCode());
verifyStatusCodeIndicateSendFailedOnly(sendStatus);
verifySendStatusIsError(sendStatus);
assertFalse(sendStatus.canProceedWithWorkflow());
}
@Test
public void shouldFailWithSendFailedExceptionWithInvalidAddresses(){
//setup
ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
MessagingException firstInnerException = new SendFailedException("Invalid Addresses <followed by a list of invalid addresses>");
throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException);
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithSendFailedException.send();
//verify
assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_INVALID_ADDRESSES_550, sendStatus.getStatusCode());
verifyStatusCodeIndicateSendFailedOnly(sendStatus);
verifySendStatusIsError(sendStatus);
assertFalse(sendStatus.canProceedWithWorkflow());
}
@Test
public void shouldFailWithSendFailedExceptionBecauseNoRecipient(){
//setup
ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
MessagingException firstInnerException = new SendFailedException("503 5.0.0 .... ");
throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException);
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithSendFailedException.send();
//verify
assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_NO_RECIPIENTS_503, sendStatus.getStatusCode());
verifyStatusCodeIndicateSendFailedOnly(sendStatus);
verifySendStatusIsError(sendStatus);
assertFalse(sendStatus.canProceedWithWorkflow());
}
@Test
public void shouldFailWithSendFailedExceptionBecauseUnknownSMTPHost(){
//setup
ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
MessagingException firstInnerException = new SendFailedException("Unknown SMTP host");
throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException);
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithSendFailedException.send();
//verify
assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_UNKNOWN_SMTP_HOST, sendStatus.getStatusCode());
verifyStatusCodeIndicateSendFailedOnly(sendStatus);
verifySendStatusIsError(sendStatus);
assertTrue(sendStatus.canProceedWithWorkflow());
}
@Test
public void shouldFailWithSendFailedExceptionBecauseCouldNotConnectToSMTPHost(){
//setup
ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
MessagingException firstInnerException = new SendFailedException("Could not connect to SMTP host");
throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException);
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithSendFailedException.send();
//verify
assertEquals(MessageSendStatusCode.SEND_FAILED_DUE_COULD_NOT_CONNECT_TO_SMTP_HOST, sendStatus.getStatusCode());
verifyStatusCodeIndicateSendFailedOnly(sendStatus);
verifySendStatusIsError(sendStatus);
assertTrue(sendStatus.canProceedWithWorkflow());
}