org.springframework.mail.MailSendException Java Examples

The following examples show how to use org.springframework.mail.MailSendException. 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: JavaMailSenderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void failedMailServerClose() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("");
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(0, ex.getFailedMessages().size());
	}
}
 
Example #2
Source File: AccountServiceImplTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
void createUserMailSendFailed()
    throws UsernameAlreadyExistsException, EmailAlreadyExistsException {

  when(idGenerator.generateId(SECURE_RANDOM)).thenReturn("3541db68-435b-416b-8c2c-cf2edf6ba435");
  doThrow(new MailSendException("mail send failed"))
      .when(mailSender)
      .send(any(SimpleMailMessage.class));

  Exception exception =
      assertThrows(
          MolgenisUserException.class,
          () -> accountService.createUser(user, "http://molgenis.org/activate"));
  assertThat(exception.getMessage())
      .containsPattern(
          "An error occurred. Please contact the administrator. You are not signed up!");
}
 
Example #3
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testSendMultipleMailsWithExceptionWhileSending() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	SimpleMailMessage firstMessage = createSimpleMailMessage();
	firstMessage.setBcc("[email protected]");

	SimpleMailMessage failureMail = createSimpleMailMessage();
	when(emailService.sendEmail(ArgumentMatchers.isA(SendEmailRequest.class)))
			.thenReturn(new SendEmailResult())
			.thenThrow(new AmazonClientException("error"))
			.thenReturn(new SendEmailResult());

	SimpleMailMessage thirdMessage = createSimpleMailMessage();

	try {
		mailSender.send(firstMessage, failureMail, thirdMessage);
		fail("Exception expected due to error while sending mail");
	}
	catch (MailSendException e) {
		assertThat(e.getFailedMessages().size()).isEqualTo(1);
		assertThat(e.getFailedMessages().containsKey(failureMail)).isTrue();
	}
}
 
Example #4
Source File: SimpleEmailServiceMailSender.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("OverloadedVarargsMethod")
@Override
public void send(SimpleMailMessage... simpleMailMessages) throws MailException {

	Map<Object, Exception> failedMessages = new HashMap<>();

	for (SimpleMailMessage simpleMessage : simpleMailMessages) {
		try {
			SendEmailResult sendEmailResult = getEmailService()
					.sendEmail(prepareMessage(simpleMessage));
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Message with id: {} successfully send",
						sendEmailResult.getMessageId());
			}
		}
		catch (AmazonClientException e) {
			// Ignore Exception because we are collecting and throwing all if any
			// noinspection ThrowableResultOfMethodCallIgnored
			failedMessages.put(simpleMessage, e);
		}
	}

	if (!failedMessages.isEmpty()) {
		throw new MailSendException(failedMessages);
	}
}
 
Example #5
Source File: NotificationServiceImplTest.java    From olat with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked" })
@Test
public void notifySubscribersFailed() {
    boolean finished = true;
    List<NotificationServiceMetric<NotificationServiceContext>> metrics = new ArrayList<NotificationServiceMetric<NotificationServiceContext>>();
    NotificationServiceMetric<? extends NotificationServiceContext> notifySuccessMetric = new AverageEmailSuccessRateMetric();
    metrics.add((NotificationServiceMetric<NotificationServiceContext>) notifySuccessMetric);
    notificationServiceImpl.setMetrics(metrics);
    when(notificationServiceImpl.notifyDelegate.notifySubscriber(any(Long.class))).thenThrow(new MailSendException("mock exception"));
    try {
        notificationServiceImpl.startNotificationJob();
        notificationServiceImpl.notifySubscriber(Long.valueOf(1));
        notificationServiceImpl.finishNotificationJob();
    } catch (MailSendException e) {

        for (NotificationServiceMetric<?> metric : metrics) {
            if (metric instanceof AverageEmailSuccessRateMetric) {
                finished = ((AverageEmailSuccessRateMetric) metric).isJobFinishedOrNotStartedYet();
            }
        }
    }
    assertTrue(finished == false);
}
 
Example #6
Source File: TransactionRetryerITCaseNew.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
// 18.04.2012/cg Hudson failed => LD or AA
// TODO: THIS METHOD HAS TO BE REMOVED; IT'S REPLACED WITH THE NEXT ONE
public void testNotifySubscribers_IfNotifyDelegateThrowsException_checkNumberOfRetriesForMailSendException() {

    Long subscriberId = new Long(1);
    NotifyDelegate mockNotifyDelegate = mock(NotifyDelegate.class);
    when(mockNotifyDelegate.notifySubscriber(subscriberId)).thenThrow(new MailSendException("mock exception"));
    notificationService.setNotifyDelegate(mockNotifyDelegate);

    try {
        verify(notificationService.notifySubscribers());
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }

    // the number of retries for MailSendException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
    verify(mockNotifyDelegate, times(4)).notifySubscriber(subscriberId);
}
 
Example #7
Source File: TransactionRetryerITCaseNew.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
// 18.04.2012/cg Hudson failed => LD or AA
// TODO: THIS METHOD HAS TO BE REMOVED; IT'S REPLACED WITH THE NEXT ONE
public void testNotifySubscribers_IfNotifyDelegateThrowsException_checkNumberOfRetriesForMailSendException() {

    Long subscriberId = new Long(1);
    NotifyDelegate mockNotifyDelegate = mock(NotifyDelegate.class);
    when(mockNotifyDelegate.notifySubscriber(subscriberId)).thenThrow(new MailSendException("mock exception"));
    notificationService.setNotifyDelegate(mockNotifyDelegate);

    try {
        verify(notificationService.notifySubscribers());
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }

    // the number of retries for MailSendException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
    verify(mockNotifyDelegate, times(4)).notifySubscriber(subscriberId);
}
 
Example #8
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void failedMailServerClose() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("");
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(0, ex.getFailedMessages().size());
	}
}
 
Example #9
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void failedMailServerConnect() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example #10
Source File: JavaMailSenderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void failedMailServerConnect() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example #11
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void failedMailServerClose() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("");
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(0, ex.getFailedMessages().size());
	}
}
 
Example #12
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void failedMailServerConnect() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example #13
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelOnly_Failed() throws Exception {
    subscriber.getChannels().remove(null);
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 1, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
}
 
Example #14
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_SucessForMail_FaildForDummy() throws Exception {
    doNothing().when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertTrue(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertFalse(statistics.getChannel2StatusMap().get(null));
}
 
Example #15
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_FailedForBoth() throws Exception {
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertFalse(statistics.getChannel2StatusMap().get(null));
}
 
Example #16
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void failedSimpleMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	simpleMessage1.setTo("[email protected]");
	simpleMessage1.setSubject("fail");
	SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
	simpleMessage2.setTo("[email protected]");

	try {
		sender.send(simpleMessage1, simpleMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(new InternetAddress("[email protected]"), sender.transport.getSentMessage(0).getAllRecipients()[0]);
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example #17
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_SucessForDummy_FaildForMail() throws Exception {
    doNothing().when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertTrue(statistics.getChannel2StatusMap().get(null));
}
 
Example #18
Source File: TransactionRetryerITCaseNew.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testSend_IfMailServiceThrowsException_checkNumberOfRetriesForMailSendException() throws Exception {
    List<NotificationEventTO> eventTOs = new ArrayList<NotificationEventTO>();
    // Test Subscriber
    Subscriber subscriber = new Subscriber();
    subscriber.setIdentity(ObjectMother.createIdentity("testUser"));

    // Mock for TemplateMailTO
    TemplateMailTO templateMailTO = mock(TemplateMailTO.class);

    // Mock for EmailBuilder
    EmailBuilder emailBuilderMock = mock(EmailBuilder.class);
    when(emailBuilderMock.getTemplateMailTO(subscriber.getIdentity().getAttributes().getEmail(), eventTOs)).thenReturn(templateMailTO);
    mailChannel.setEmailBuilder(emailBuilderMock);

    // Mock for MailService
    MailService mailServiceMock = mock(MailService.class);
    doThrow(new MailSendException("MailService: Test Exception")).when(mailServiceMock).sendMailWithTemplate(templateMailTO);
    mailChannel.setMailService(mailServiceMock);

    try {
        mailChannel.send(subscriber, eventTOs);
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }

    verify(mailServiceMock, times(4)).sendMailWithTemplate(templateMailTO);
}
 
Example #19
Source File: TransactionRetryerITCaseNew.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Assumes that ConstraintViolationException could be retried once while MailSendException could be retried 3 times, see lmsLearnTestContext.xml for
 * maxRetriesPerException.
 */
@Test
public void isRetryStillAllowed_twoExceptionTypes_moreRetriesAllowed() {
    Map<String, Long> retriesPerException = new HashMap<String, Long>();
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry for ConstraintViolationException
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    for (int i = 0; i < 3; i++) {
        // retry for MailSendException
        transactionRetryer.addOrIncrementRetries(retriesPerException, MailSendException.class.getName());
        assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));
    }

    // retry for MailSendException - isRetryStillAllowed should return false since MailSendException is configured to be retried 3 times
    transactionRetryer.addOrIncrementRetries(retriesPerException, MailSendException.class.getName());
    boolean isMailSendExceptionRetryAllowed = transactionRetryer.isRetryStillAllowed(retriesPerException);

    // retry second time no more allowed - throw error further
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    boolean isConstraintViolationExceptionAllowed = transactionRetryer.isRetryStillAllowed(retriesPerException);

    assertFalse(isMailSendExceptionRetryAllowed);
    assertFalse(isConstraintViolationExceptionAllowed);

    // retry no more allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
}
 
Example #20
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelOnly_Failed() throws Exception {
    subscriber.getChannels().remove(null);
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 1, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
}
 
Example #21
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_FailedForBoth() throws Exception {
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertFalse(statistics.getChannel2StatusMap().get(null));
}
 
Example #22
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_SucessForMail_FaildForDummy() throws Exception {
    doNothing().when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertTrue(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertFalse(statistics.getChannel2StatusMap().get(null));
}
 
Example #23
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_SucessForDummy_FaildForMail() throws Exception {
    doNothing().when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertTrue(statistics.getChannel2StatusMap().get(null));
}
 
Example #24
Source File: ChannelChainTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotifyStatistics_send_failedForMail() throws Exception {
    doNothing().when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals(1, statistics.getFailedCounter());
    assertEquals(1, statistics.getDeliveredCounter());
    assertEquals(2, statistics.getTotalCounter()); // 2 since 2 channels
}
 
Example #25
Source File: FileServiceImpl.java    From seppb with MIT License 5 votes vote down vote up
@Override
public void sendAttachMail(TestMail testMail) {
    User user = userDAO.findUserByUserId(ParameterThreadLocal.getUserId());
    String body = testMail.getBody().concat(String.format(EMAIL_FOOTER, user.getUserName(), user.getUserEmail()));
    MailDTO mailDTO;
    if (!isEmpty(testMail.getCc())) {
        mailDTO = MailDTO.builder().from(fromEmail)
                .to(testMail.getTo())
                .tocc(testMail.getCc())
                .content(body)
                .isHtml(true)
                .subject(testMail.getSubject())
                .build();
    } else {
        mailDTO = MailDTO.builder().from(fromEmail)
                .to(testMail.getTo())
                .content(body)
                .isHtml(true)
                .subject(testMail.getSubject())
                .build();
    }
    try {
        JavaMailUtils.sendMail(mailDTO);
    } catch (MailSendException ne) {
        if (ne.getMessage().indexOf("550 User not found") > 0) {
            log.error("邮件地址不存在", ne.getMessage());
        } else {
            throw new SeppServerException("邮件发送失败,请重试", ne);
        }
    } catch (Exception e) {
        throw new SeppServerException("邮件发送失败,请重试", e);
    }
}
 
Example #26
Source File: JavaMailSenderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void failedMimeMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage1.setSubject("fail");
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

	try {
		sender.send(mimeMessage1, mimeMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(mimeMessage2, sender.transport.getSentMessage(0));
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(mimeMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example #27
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("OverloadedVarargsMethod")
@Override
public void send(MimeMessage... mimeMessages) throws MailException {
	Map<Object, Exception> failedMessages = new HashMap<>();

	for (MimeMessage mimeMessage : mimeMessages) {
		try {
			RawMessage rm = createRawMessage(mimeMessage);
			SendRawEmailResult sendRawEmailResult = getEmailService()
					.sendRawEmail(new SendRawEmailRequest(rm));
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Message with id: {} successfully send",
						sendRawEmailResult.getMessageId());
			}
			mimeMessage.setHeader("Message-ID", sendRawEmailResult.getMessageId());
		}
		catch (Exception e) {
			// Ignore Exception because we are collecting and throwing all if any
			// noinspection ThrowableResultOfMethodCallIgnored
			failedMessages.put(mimeMessage, e);
		}
	}

	if (!failedMessages.isEmpty()) {
		throw new MailSendException(failedMessages);
	}
}
 
Example #28
Source File: JavaMailSenderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void failedSimpleMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	simpleMessage1.setTo("[email protected]");
	simpleMessage1.setSubject("fail");
	SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
	simpleMessage2.setTo("[email protected]");

	try {
		sender.send(simpleMessage1, simpleMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(new InternetAddress("[email protected]"), sender.transport.getSentMessage(0).getAllRecipients()[0]);
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example #29
Source File: FeedbackControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void submitErrorWhileSendingMail() throws Exception {
  List<String> adminEmails = Collections.singletonList("[email protected]");
  when(userService.getSuEmailAddresses()).thenReturn(adminEmails);
  when(appSettings.getRecaptchaIsEnabled()).thenReturn(true);
  when(reCaptchaService.validate("validCaptcha")).thenReturn(true);
  SimpleMailMessage expected = new SimpleMailMessage();
  expected.setTo("[email protected]");
  expected.setCc("[email protected]");
  expected.setReplyTo("[email protected]");
  expected.setSubject("[feedback-app123] Feedback form");
  expected.setText("Feedback from First Last ([email protected]):\n\n" + "Feedback.\nLine two.");
  doThrow(new MailSendException("ERRORRR!")).when(mailSender).send(expected);
  mockMvcFeedback
      .perform(
          MockMvcRequestBuilders.post(FeedbackController.URI)
              .param("name", "First Last")
              .param("subject", "Feedback form")
              .param("email", "[email protected]")
              .param("feedback", "Feedback.\nLine two.")
              .param("recaptcha", "validCaptcha"))
      .andExpect(status().isOk())
      .andExpect(view().name("view-feedback"))
      .andExpect(model().attribute("feedbackForm", hasProperty("submitted", equalTo(false))))
      .andExpect(
          model()
              .attribute(
                  "feedbackForm",
                  hasProperty(
                      "errorMessage",
                      equalTo(
                          "Unfortunately, we were unable to send the mail containing "
                              + "your feedback. Please contact the administrator."))));
  verify(reCaptchaService, times(1)).validate("validCaptcha");
}
 
Example #30
Source File: MailServiceImplTest.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure if we can't send an email an exception is thrown.
 *
 * @throws GenieException On error
 */
@Test(expected = GenieServerException.class)
public void cantSendEmail() throws GenieException {
    final String to = UUID.randomUUID().toString();
    final String subject = UUID.randomUUID().toString();
    final String body = UUID.randomUUID().toString();

    Mockito.doThrow(new MailSendException("a")).when(this.mailSender).send(Mockito.any(SimpleMailMessage.class));
    this.mailService.sendEmail(to, subject, body);
}