Java Code Examples for org.springframework.mail.SimpleMailMessage#setCc()

The following examples show how to use org.springframework.mail.SimpleMailMessage#setCc() . 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: SpringMailSenderBackend.java    From haven-platform with Apache License 2.0 7 votes vote down vote up
@Override
public void send(MailMessage message) throws MailSenderException {
    SimpleMailMessage smm = new SimpleMailMessage();
    MailBody body = message.getBody();
    smm.setText(MailUtils.toPlainText(body));
    MailHead head = message.getHead();
    smm.setFrom(head.getFrom());
    smm.setReplyTo(head.getReplyTo());
    smm.setSubject(head.getSubject());
    smm.setTo(asArray(head.getTo()));
    smm.setCc(asArray(head.getCc()));
    smm.setBcc(asArray(head.getBcc()));
    smm.setSentDate(head.getSentDate());
    LOG.info("message to send {}", smm);
    mailSender.send(smm);
}
 
Example 2
Source File: EmailMessageSender.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 处理简单邮件类型
 *
 * @param message 邮件内容
 * @return boolean
 */
private boolean processSimpleEmail(EmailMessage message) {
	// 注意邮件发送可能出现异常,注意catch
	try {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setFrom("\"" + message.getFrom() + "\" <" + username + ">");
		simpleMailMessage.setTo(ArrayUtil.toArray(message.getTos(), String.class));
		simpleMailMessage.setSubject(message.getSubject());
		simpleMailMessage.setText(message.getContent());

		// 设置抄送人列表
		if (CollUtil.isEmpty(message.getCcs())) {
			simpleMailMessage.setCc(ArrayUtil.toArray(message.getCcs(), String.class));
		}
		mailSender.send(simpleMailMessage);
		return true;
	} catch (Exception e) {
		log.error("简单邮件发送异常!", e);
		return false;
	}
}
 
Example 3
Source File: FeedbackController.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Creates a MimeMessage based on a FeedbackForm. */
@SuppressWarnings("java:S3457") // do not use platform specific line ending
private SimpleMailMessage createFeedbackMessage(FeedbackForm form) {
  SimpleMailMessage message = new SimpleMailMessage();
  message.setTo(userService.getSuEmailAddresses().toArray(new String[] {}));
  if (form.hasEmail()) {
    message.setCc(form.getEmail());
    message.setReplyTo(form.getEmail());
  } else {
    message.setReplyTo("[email protected]");
  }
  String appName = appSettings.getTitle();
  message.setSubject(String.format("[feedback-%s] %s", appName, form.getSubject()));
  message.setText(String.format("Feedback from %s:\n\n%s", form.getFrom(), form.getFeedback()));
  return message;
}
 
Example 4
Source File: MailerImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
    * Construct and a send simple email message from a Mail Message.
    * 
    * @param message
    *            the Mail Message
 * @throws MessagingException 
    */
@Override
      @SuppressWarnings("unchecked")
public void sendEmail(MailMessage message) throws MessagingException {
       
       // Construct a simple mail message from the Mail Message
       SimpleMailMessage smm = new SimpleMailMessage();
       smm.setTo( (String[])message.getToAddresses().toArray(new String[message.getToAddresses().size()]) );
       smm.setBcc( (String[])message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]) );
       smm.setCc( (String[])message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]) );
       smm.setSubject(message.getSubject());
       smm.setText(message.getMessage());
       smm.setFrom(message.getFromAddress());

       try {
       	if ( LOG.isDebugEnabled() ) {
       		LOG.debug( "sendEmail() - Sending message: " + smm.toString() );
       	}
           mailSender.send(smm);
       }
       catch (Exception e) {
       	LOG.error("sendEmail() - Error sending email.", e);
		throw new RuntimeException(e);
       }
   }
 
Example 5
Source File: MailServiceImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @throws MailException
 *             general super class for all mail-exception when send failed
 * @throws MailParseException
 *             in case of failure when parsing the message
 * @throws MailAuthenticationException
 *             in case of authentication failure
 * @throws MailSendException
 *             in case of failure when sending the message
 */
@Override
public void sendSimpleMail(SimpleMailTO mailParameters) throws MailException {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(mailParameters.getToMailAddress());
    msg.setFrom(mailParameters.getFromMailAddress());
    msg.setSubject(mailParameters.getSubject());
    msg.setText(mailParameters.getBodyText());
    if (mailParameters.hasCcMailAddress()) {
        msg.setCc(mailParameters.getCcMailAddress());
    }
    if (mailParameters.hasReplyTo()) {
        msg.setReplyTo(mailParameters.getReplyTo());
    }
    mailSender.send(msg);
}
 
Example 6
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 发送文本邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param cc      抄送地址
 */
@Override
public void sendSimpleMail(String to, String subject, String content, String... cc) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    if (ArrayUtil.isNotEmpty(cc)) {
        message.setCc(cc);
    }
    mailSender.send(message);
}
 
Example 7
Source File: FeedbackControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void submitAuthenticationErrorWhileSendingMail() 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 MailAuthenticationException("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 8
Source File: FeedbackControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void submit() 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);
  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(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.");
  verify(mailSender, times(1)).send(expected);
  verify(reCaptchaService, times(1)).validate("validCaptcha");
}
 
Example 9
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testSendSimpleMailWithCCandBCC() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

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

	ArgumentCaptor<SendEmailRequest> request = ArgumentCaptor
			.forClass(SendEmailRequest.class);
	when(emailService.sendEmail(request.capture()))
			.thenReturn(new SendEmailResult().withMessageId("123"));

	mailSender.send(simpleMailMessage);

	SendEmailRequest sendEmailRequest = request.getValue();
	assertThat(sendEmailRequest.getSource()).isEqualTo(simpleMailMessage.getFrom());
	assertThat(sendEmailRequest.getDestination().getToAddresses().get(0))
			.isEqualTo(simpleMailMessage.getTo()[0]);
	assertThat(sendEmailRequest.getMessage().getSubject().getData())
			.isEqualTo(simpleMailMessage.getSubject());
	assertThat(sendEmailRequest.getMessage().getBody().getText().getData())
			.isEqualTo(simpleMailMessage.getText());
	assertThat(sendEmailRequest.getDestination().getBccAddresses().get(0))
			.isEqualTo(simpleMailMessage.getBcc()[0]);
	assertThat(sendEmailRequest.getDestination().getCcAddresses().get(0))
			.isEqualTo(simpleMailMessage.getCc()[0]);
}
 
Example 10
Source File: MailServiceImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @throws MailException
 *             general super class for all mail-exception when send failed
 * @throws MailParseException
 *             in case of failure when parsing the message
 * @throws MailAuthenticationException
 *             in case of authentication failure
 * @throws MailSendException
 *             in case of failure when sending the message
 */
public void sendSimpleMail(SimpleMailTO mailParameters) throws MailException {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(mailParameters.getToMailAddress());
    msg.setFrom(mailParameters.getFromMailAddress());
    msg.setSubject(mailParameters.getSubject());
    msg.setText(mailParameters.getBodyText());
    if (mailParameters.hasCcMailAddress()) {
        msg.setCc(mailParameters.getCcMailAddress());
    }
    if (mailParameters.hasReplyTo()) {
        msg.setReplyTo(mailParameters.getReplyTo());
    }
    mailSender.send(msg);
}
 
Example 11
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 12
Source File: MailMessageNotifier.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Send mail messages.
 *
 * @param simpleMessages
 */
@Override
public void send(GenericNotifyMessage msg) {
    String mailMsgType = msg.getParameterAsString(KEY_MAILMSG_TYPE, "simple");
    switch (mailMsgType) {
        case KEY_MAILMSG_VALUE_SIMPLE:
            SimpleMailMessage simpleMsg = new SimpleMailMessage();
            // Add "<>" symbol to send out?
            /*
             * Preset from account, otherwise it would be wrong: 501 mail from
             * address must be same as authorization user.
             */
            simpleMsg.setFrom(config.getUsername() + "<" + config.getUsername() + ">");
            simpleMsg.setTo(msg.getToObjects().stream().map(to -> to = to + "<" + to + ">").collect(toList()).toArray(new String[]{}));
            simpleMsg.setSubject(msg.getParameterAsString(KEY_MAILMSG_SUBJECT, "Super Devops Messages"));
            simpleMsg.setSentDate(msg.getParameter(KEY_MSG_SENDDATE, new Date()));
            simpleMsg.setBcc(safeList(msg.getParameter(KEY_MAILMSG_BCC)).toArray(new String[]{}));
            simpleMsg.setCc(safeList(msg.getParameter(KEY_MAILMSG_CC)).toArray(new String[]{}));
            simpleMsg.setReplyTo(msg.getParameter(KEY_MAILMSG_REPLYTO));
            simpleMsg.setText(config.getResolvedMessage(msg.getTemplateKey(), msg.getParameters()));

            mailSender.send(simpleMsg);
            break;
        case KEY_MAILMSG_VALUE_MIME: // TODO implements!!!
            log.warn("No implements MimeMailMessage!!!");
            break;
        default:
            throw new UnsupportedOperationException(format("No supported mail message type of %s", mailMsgType));
    }

}
 
Example 13
Source File: MailServiceImpl.java    From mySpringBoot with Apache License 2.0 5 votes vote down vote up
/**
 * 发送简单邮件
 */
@Override
public void sendSimpleMail(Mail mail){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(mail.getTo());
    message.setSubject(mail.getSubject());
    message.setText(mail.getText());
    message.setCc(mail.getCc());
    mailSender.send(message);
}
 
Example 14
Source File: EmailSupport.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
public void reportLaunchError(JobSpec spec, Throwable t) {

        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo(String.format("%[email protected]", spec.getUser()));
        msg.setFrom("[email protected]");
        msg.setCc("[email protected]");
        msg.setSubject("Failed to launch OpenCue job.");

        StringBuilder sb = new StringBuilder(131072);
        sb.append("This is an automatic message from cuebot that is sent");
        sb.append(" after a queued\njob has failed to launch. This usually");
        sb.append(" occurs if you have made a mistake\nediting an outline");
        sb.append(" script. If you have no idea why you are receiving\nthis");
        sb.append(" message and your jobs are not hitting the cue, please");
        sb.append(" open a\nhelpdesk ticket with the debugging information");
        sb.append(" provided below.\n\n");

        sb.append("Failed to launch jobs:\n");
        for (BuildableJob job: spec.getJobs()) {
            sb.append(job.detail.name);
            sb.append("\n");
        }
        sb.append("\n\n");
        sb.append(new XMLOutputter(
                Format.getPrettyFormat()).outputString(spec.getDoc()));
        sb.append("\n\n");
        sb.append(CueExceptionUtil.getStackTrace(t));

        String body = sb.toString();
        msg.setText(body);
        sendMessage(msg);
    }
 
Example 15
Source File: MailEventNotifier.java    From earth-frost with Apache License 2.0 5 votes vote down vote up
@Override
protected void doNotify(Event event) {

  JobInfo jobInfo = Container.get().getJobRepository()
      .findJobInfoById(event.getData().getJobId());
  if (jobInfo == null) {
    return;
  }

  Map<String, Object> attrs = MoreObjects.mapOf("event", event, "job", jobInfo);

  String subjectVal = ENGINE.render(DEFAULT_SUBJECT, attrs);
  String textVal = ENGINE.render(DEFAULT_TEXT, attrs);

  SimpleMailMessage message = new SimpleMailMessage();

  String[] mails = jobInfo.getNotifyMails();
  String[] dest;
  if (mails != null) {
    dest = Arrays.copyOf(mails, mails.length + to.length);
    System.arraycopy(to, 0, dest, mails.length, to.length);
  } else {
    dest = to;
  }
  message.setTo(dest);
  message.setFrom(from);
  message.setSubject(subjectVal);
  message.setText(textVal);
  message.setCc(cc);

  sender.send(message);
}
 
Example 16
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 发送文本邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param cc      抄送地址
 */
@Override
public void sendSimpleMail(String to, String subject, String content, String... cc) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    if (ArrayUtil.isNotEmpty(cc)) {
        message.setCc(cc);
    }
    mailSender.send(message);
}
 
Example 17
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 发送文本邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param cc      抄送地址
 */
@Override
public void sendSimpleMail(String to, String subject, String content, String... cc) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    message.setCc(cc);

    mailSender.send(message);
}
 
Example 18
Source File: JavaMailSenderTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void javaMailSenderWithSimpleMessage() throws MessagingException, IOException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setPort(30);
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage = new SimpleMailMessage();
	simpleMessage.setFrom("[email protected]");
	simpleMessage.setReplyTo("[email protected]");
	simpleMessage.setTo("[email protected]");
	simpleMessage.setCc("[email protected]", "[email protected]");
	simpleMessage.setBcc("[email protected]", "[email protected]");
	Date sentDate = new GregorianCalendar(2004, 1, 1).getTime();
	simpleMessage.setSentDate(sentDate);
	simpleMessage.setSubject("my subject");
	simpleMessage.setText("my text");
	sender.send(simpleMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals(30, sender.transport.getConnectedPort());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());

	assertEquals(1, sender.transport.getSentMessages().size());
	MimeMessage sentMessage = sender.transport.getSentMessage(0);
	List<Address> froms = Arrays.asList(sentMessage.getFrom());
	assertEquals(1, froms.size());
	assertEquals("[email protected]", ((InternetAddress) froms.get(0)).getAddress());
	List<Address> replyTos = Arrays.asList(sentMessage.getReplyTo());
	assertEquals("[email protected]", ((InternetAddress) replyTos.get(0)).getAddress());
	List<Address> tos = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.TO));
	assertEquals(1, tos.size());
	assertEquals("[email protected]", ((InternetAddress) tos.get(0)).getAddress());
	List<Address> ccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.CC));
	assertEquals(2, ccs.size());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(1)).getAddress());
	List<Address> bccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.BCC));
	assertEquals(2, bccs.size());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(1)).getAddress());
	assertEquals(sentDate.getTime(), sentMessage.getSentDate().getTime());
	assertEquals("my subject", sentMessage.getSubject());
	assertEquals("my text", sentMessage.getContent());
}
 
Example 19
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void javaMailSenderWithSimpleMessage() throws MessagingException, IOException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setPort(30);
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage = new SimpleMailMessage();
	simpleMessage.setFrom("[email protected]");
	simpleMessage.setReplyTo("[email protected]");
	simpleMessage.setTo("[email protected]");
	simpleMessage.setCc(new String[] {"[email protected]", "[email protected]"});
	simpleMessage.setBcc(new String[] {"[email protected]", "[email protected]"});
	Date sentDate = new GregorianCalendar(2004, 1, 1).getTime();
	simpleMessage.setSentDate(sentDate);
	simpleMessage.setSubject("my subject");
	simpleMessage.setText("my text");
	sender.send(simpleMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals(30, sender.transport.getConnectedPort());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());

	assertEquals(1, sender.transport.getSentMessages().size());
	MimeMessage sentMessage = sender.transport.getSentMessage(0);
	List<Address> froms = Arrays.asList(sentMessage.getFrom());
	assertEquals(1, froms.size());
	assertEquals("[email protected]", ((InternetAddress) froms.get(0)).getAddress());
	List<Address> replyTos = Arrays.asList(sentMessage.getReplyTo());
	assertEquals("[email protected]", ((InternetAddress) replyTos.get(0)).getAddress());
	List<Address> tos = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.TO));
	assertEquals(1, tos.size());
	assertEquals("[email protected]", ((InternetAddress) tos.get(0)).getAddress());
	List<Address> ccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.CC));
	assertEquals(2, ccs.size());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(1)).getAddress());
	List<Address> bccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.BCC));
	assertEquals(2, bccs.size());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(1)).getAddress());
	assertEquals(sentDate.getTime(), sentMessage.getSentDate().getTime());
	assertEquals("my subject", sentMessage.getSubject());
	assertEquals("my text", sentMessage.getContent());
}
 
Example 20
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void javaMailSenderWithSimpleMessage() throws MessagingException, IOException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setPort(30);
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage = new SimpleMailMessage();
	simpleMessage.setFrom("[email protected]");
	simpleMessage.setReplyTo("[email protected]");
	simpleMessage.setTo("[email protected]");
	simpleMessage.setCc("[email protected]", "[email protected]");
	simpleMessage.setBcc("[email protected]", "[email protected]");
	Date sentDate = new GregorianCalendar(2004, 1, 1).getTime();
	simpleMessage.setSentDate(sentDate);
	simpleMessage.setSubject("my subject");
	simpleMessage.setText("my text");
	sender.send(simpleMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals(30, sender.transport.getConnectedPort());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());

	assertEquals(1, sender.transport.getSentMessages().size());
	MimeMessage sentMessage = sender.transport.getSentMessage(0);
	List<Address> froms = Arrays.asList(sentMessage.getFrom());
	assertEquals(1, froms.size());
	assertEquals("[email protected]", ((InternetAddress) froms.get(0)).getAddress());
	List<Address> replyTos = Arrays.asList(sentMessage.getReplyTo());
	assertEquals("[email protected]", ((InternetAddress) replyTos.get(0)).getAddress());
	List<Address> tos = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.TO));
	assertEquals(1, tos.size());
	assertEquals("[email protected]", ((InternetAddress) tos.get(0)).getAddress());
	List<Address> ccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.CC));
	assertEquals(2, ccs.size());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(1)).getAddress());
	List<Address> bccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.BCC));
	assertEquals(2, bccs.size());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(1)).getAddress());
	assertEquals(sentDate.getTime(), sentMessage.getSentDate().getTime());
	assertEquals("my subject", sentMessage.getSubject());
	assertEquals("my text", sentMessage.getContent());
}