当前位置: 首页>>代码示例>>Java>>正文


Java MailSendException类代码示例

本文整理汇总了Java中org.springframework.mail.MailSendException的典型用法代码示例。如果您正苦于以下问题:Java MailSendException类的具体用法?Java MailSendException怎么用?Java MailSendException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


MailSendException类属于org.springframework.mail包,在下文中一共展示了MailSendException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: failedMailServerConnect

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@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());
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:21,代码来源:JavaMailSenderTests.java

示例2: failedMailServerClose

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@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());
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:19,代码来源:JavaMailSenderTests.java

示例3: saveUser

import org.springframework.mail.MailSendException; //导入依赖的package包/类
/**
 * Creates user
 *
 * @param user user to be created
 */
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/users/create", method = RequestMethod.POST)
public void saveUser(@RequestBody UserDto user) {
    int passLength = Math.max(GENERATED_PASSWORD_MIN_LENGTH, settingService.getMinPasswordLength());
    String password = user.isGeneratePassword() ? RandomStringUtils.randomAlphanumeric(passLength) : user.getPassword();

    motechUserService.register(user.getUserName(), password, user.getEmail(), "", user.getRoles(), user.getLocale());

    try {
        if (user.isGeneratePassword() && StringUtils.isNotBlank(user.getEmail())) {
            motechUserService.sendLoginInformation(user.getUserName());
        }
    } catch (UserNotFoundException | NonAdminUserException | ServerUrlIsEmptyException ex) {
        throw new MailSendException("Email was not sent", ex);
    }
}
 
开发者ID:motech,项目名称:motech,代码行数:22,代码来源:UserController.java

示例4: testNotifySubscribers_IfNotifyDelegateThrowsException_checkNumberOfRetriesForMailSendException

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@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);
}
 
开发者ID:huihoo,项目名称:olat,代码行数:21,代码来源:TransactionRetryerITCaseNew.java

示例5: notifySubscribersFailed

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@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);
}
 
开发者ID:huihoo,项目名称:olat,代码行数:24,代码来源:NotificationServiceImplTest.java

示例6: create

import org.springframework.mail.MailSendException; //导入依赖的package包/类
private SendMailBatch create(long intervalMillis, File shutdownTrigger, boolean sendMailException) {

		bizDateTime = mock(BizDateTime.class);
		mailSendHandler = mock(MailSendHandler.class);
		when(mailSendHandler.listMessage((LocalDateTime) any())).thenReturn(asList(1L, 2L, 3L));
		if (sendMailException) {
			when(mailSendHandler.sendMessage(anyLong())).thenThrow(new MailSendException("sending mail failed"));
		}

		SendMailBatch batch = new SendMailBatch();
		batch.setBizDateTime(bizDateTime);
		batch.setMailSendHandler(mailSendHandler);
		batch.setIntervalMillis(intervalMillis);
		batch.setShutdownTrigger(shutdownTrigger);
		return batch;
	}
 
开发者ID:agwlvssainokuni,项目名称:sqlapp,代码行数:17,代码来源:SendMailBatchTest.java

示例7: testFailedMailServerConnect

import org.springframework.mail.MailSendException; //导入依赖的package包/类
public void testFailedMailServerConnect() 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());
	}
}
 
开发者ID:deathspeeder,项目名称:class-guard,代码行数:20,代码来源:JavaMailSenderTests.java

示例8: testFailedMailServerClose

import org.springframework.mail.MailSendException; //导入依赖的package包/类
public void testFailedMailServerClose() 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());
	}
}
 
开发者ID:deathspeeder,项目名称:class-guard,代码行数:18,代码来源:JavaMailSenderTests.java

示例9: send

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-aws,代码行数:24,代码来源:SimpleEmailServiceMailSender.java

示例10: send

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@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());
            }
        } 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);
    }
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-aws,代码行数:24,代码来源:SimpleEmailServiceJavaMailSender.java

示例11: testSendMultipleMailsWithExceptionWhileSending

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@Test
public 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) {
        assertEquals(1, e.getFailedMessages().size());
        assertTrue(e.getFailedMessages().containsKey(failureMail));
    }
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-aws,代码行数:25,代码来源:SimpleEmailServiceMailSenderTest.java

示例12: testSendMultipleMailsWithException

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@Test
public void testSendMultipleMailsWithException() throws Exception {
    AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);

    JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService);

    MimeMessage failureMail = createMimeMessage();
    when(emailService.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class))).
            thenReturn(new SendRawEmailResult()).
            thenThrow(new AmazonClientException("error")).
            thenReturn(new SendRawEmailResult());

    try {
        mailSender.send(createMimeMessage(), failureMail, createMimeMessage());
        fail("Exception expected due to error while sending mail");
    } catch (MailSendException e) {
        assertEquals(1, e.getFailedMessages().size());
        assertTrue(e.getFailedMessages().containsKey(failureMail));
    }
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-aws,代码行数:21,代码来源:SimpleEmailServiceJavaMailSenderTest.java

示例13: writeMailMessageToFile

import org.springframework.mail.MailSendException; //导入依赖的package包/类
public void writeMailMessageToFile(final SimpleMailMessage mailMessage) {
	String[] to = mailMessage.getTo();
	String text = mailMessage.getText();
	String subject = mailMessage.getSubject();

	StringBuilder str = new StringBuilder();
	str.append(subject).append("\r\n\r\n").append(text);

	File mailFile = new File(mailMockDir + System.getProperty("file.separator") + getMailFileName(to[0], (text+subject).hashCode()));
	try {
		FileUtils.writeStringToFile(mailFile, str.toString(), "UTF-8");
	}
	catch (IOException e) {
		throw new MailSendException(e.getMessage(), e);
	}
}
 
开发者ID:Clemens85,项目名称:runningdinner,代码行数:17,代码来源:MailSenderMockFile.java

示例14: submitErrorWhileSendingMail

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@Test
public void submitErrorWhileSendingMail() throws Exception
{
	List<String> adminEmails = Collections.singletonList("[email protected]");
	when(userService.getSuEmailAddresses()).thenReturn(adminEmails);
	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("captcha", "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(captchaService, times(1)).validateCaptcha("validCaptcha");
}
 
开发者ID:molgenis,项目名称:molgenis,代码行数:27,代码来源:FeedbackControllerTest.java

示例15: failToSendEmailRegistrationToken_shouldNotThrowException

import org.springframework.mail.MailSendException; //导入依赖的package包/类
@Test
public void failToSendEmailRegistrationToken_shouldNotThrowException() {
	String registrationConfigUri = String.format(CONFIG_URI, TokenType.REGISTRATION_MAIL.toString().toLowerCase());
	doReturn(TOKEN).when(token).getToken();
	doThrow(new MailSendException("")).when(mailServer).send((SimpleMailMessage) any());

	doReturn("dummyUrl/%1$d/%2$s").when(messageSource).getMessage(registrationConfigUri + ".url", null, null);
	doReturn("Subject").when(messageSource).getMessage(registrationConfigUri + ".subject", null, null);
	doReturn("Body %1$s %2$s").when(messageSource).getMessage(registrationConfigUri + ".body", null, null);

	tokenDeliverySystem.sendTokenToUser(token, user, TokenType.REGISTRATION_MAIL);
}
 
开发者ID:oojorgeoo89,项目名称:QuizZz,代码行数:13,代码来源:TokenDeliverySystemEmailTests.java


注:本文中的org.springframework.mail.MailSendException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。