javax.mail.SendFailedException Java Examples

The following examples show how to use javax.mail.SendFailedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SendEMail.java    From tn5250j with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);


}
 
Example #2
Source File: BouncerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: MailDelivrer.java    From james-project with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #6
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #11
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #12
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #13
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());	
}
 
Example #14
Source File: ExceptionHandlingMailSendingTemplate.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: Emailer.java    From olat with Apache License 2.0 5 votes vote down vote up
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;
    }
 
Example #16
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #17
Source File: EmailService.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void sendMessages() throws MessagingException {
    Transport transport = null;
    try {
        URLName url = new URLName("smtp", host, port, "", username, password);
        if (session == null) {
            createSession();
        }
        transport = new com.sun.mail.smtp.SMTPTransport(session, url);
        transport.connect(host, port, username, password);
        for (MimeMessage message : messages) {
            // Attempt to send message, but catch exceptions caused by invalid
            // addresses so that other messages can continue to be sent.
            try {
                transport.sendMessage(message,
                    message.getRecipients(MimeMessage.RecipientType.TO));
            }
            catch (AddressException | SendFailedException ae) {
                Log.error(ae.getMessage(), ae);
            }
        }
    }
    finally {
        if (transport != null) {
            try {
                transport.close();
            }
            catch (MessagingException e) { /* ignore */ }
        }
    }
}
 
Example #18
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #19
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #20
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #21
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #22
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #23
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailWithSendFailedExceptionWithAnAuthenticationFailedException(){
	//setup
	ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
		@Override
		protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
			assertNotNull("emailer was constructed", emailer);
			MessagingException firstInnerException = new AuthenticationFailedException("<some authentication failed 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.SMTP_AUTHENTICATION_FAILED, sendStatus.getStatusCode());
	verifyStatusCodeIndicateSendFailedOnly(sendStatus);
	verifySendStatusIsError(sendStatus);
	assertTrue(sendStatus.canProceedWithWorkflow());
}
 
Example #24
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailWithOLATRuntimeExceptionWithAnUnhandletSendFailedException(){
	//setup
	ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
		@Override
		protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
			assertNotNull("emailer was constructed", emailer);
			MessagingException firstInnerException = new SendFailedException("unhandled sendfail exception");
			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
	try{	
		MessageSendStatus sendStatus = doSendWithSendFailedException.send();
		fail("OLATRuntime exception is not thrown.");
	}catch(OLATRuntimeException ore){
		assertNotNull(ore);
	}
	
}
 
Example #25
Source File: ExceptionHandlingMailSendingTemplateTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Theory
public void shouldFailWithErrorWithAnyOtherMessagingException(final MessagingException me){
	//setup
	ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
		@Override
		protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
			assertNotNull("emailer was constructed", emailer);
			throw me;
		}
		
		@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.MAIL_CONTENT_NOK, sendStatus.getStatusCode());
	verifyStatusCodeIndicateMessagingExcpetionOnly(sendStatus);
	verifySendStatusIsWarn(sendStatus);
	assertFalse(sendStatus.canProceedWithWorkflow());
	
}
 
Example #26
Source File: EmailerTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testSystemEmailerSetupBySendingAMessageFromAdminToInfo() throws AddressException, SendFailedException, MessagingException{
	//Setup
	//Exercise
	systemEmailer.sendEmail(ObjectMother.OLATINFO_EMAIL, ObjectMother.AN_EXAMPLE_SUBJECT, ObjectMother.HELLOY_KITTY_THIS_IS_AN_EXAMPLE_BODY);
	//Verify
	verify(webappAndMailhelperMockSystemMailer, times(1)).send(any(MimeMessage.class), any(MailerResult.class));
	assertEquals("system is mail sender", ObjectMother.OLATADMIN_EMAIL, systemEmailer.mailfrom);
}
 
Example #27
Source File: EmailerTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldNotSendAnEmailWithDisabledMailHost() throws AddressException, SendFailedException, MessagingException{
	//Setup 
	MailPackageStaticDependenciesWrapper webappAndMailhelperMock = createWebappAndMailhelperWithDisabledMailFunctinality();
	Emailer anEmailer = new Emailer(mailTemplateMockForSystemMailer, webappAndMailhelperMock);
	//Exercise
	anEmailer.sendEmail(ObjectMother.OLATINFO_EMAIL, ObjectMother.AN_EXAMPLE_SUBJECT, ObjectMother.HELLOY_KITTY_THIS_IS_AN_EXAMPLE_BODY);
	//Verify
	verify(webappAndMailhelperMock, never()).send(any(MimeMessage.class), any(MailerResult.class));
}
 
Example #28
Source File: MailDelivrer.java    From james-project with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #29
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@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));
}