Java Code Examples for javax.mail.Message

The following examples show how to use javax.mail.Message. These examples are extracted from open source projects. 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 Project: fido2   Source File: EmailService.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public void sendEmail(String email, String subjectline, String content) throws UnsupportedEncodingException{
    try{
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(
                Configurations.getConfigurationProperty("poc.cfg.property.smtp.from"),
                Configurations.getConfigurationProperty("poc.cfg.property.smtp.fromName")));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject(subjectline);

        if(Configurations.getConfigurationProperty("poc.cfg.property.email.type").equalsIgnoreCase("HTML")){
            message.setContent(content, "text/html; charset=utf-8");
        }
        else{
            message.setText(content);
        }

        Transport.send(message);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        POCLogger.logp(Level.SEVERE, CLASSNAME, "callSKFSRestApi", "POC-ERR-5001", ex.getLocalizedMessage());
    }
}
 
Example 2
Source Project: nomulus   Source File: SendEmailServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_simple() throws Exception {
  EmailMessage content = createBuilder().build();
  sendEmailService.sendEmail(content);
  Message message = getMessage();
  assertThat(message.getAllRecipients())
      .asList()
      .containsExactly(new InternetAddress("[email protected]"));
  assertThat(message.getFrom())
      .asList()
      .containsExactly(new InternetAddress("[email protected]"));
  assertThat(message.getRecipients(RecipientType.BCC)).isNull();
  assertThat(message.getSubject()).isEqualTo("Subject");
  assertThat(message.getContentType()).startsWith("multipart/mixed");
  assertThat(getInternalContent(message).getContent().toString()).isEqualTo("body");
  assertThat(getInternalContent(message).getContentType()).isEqualTo("text/plain; charset=utf-8");
  assertThat(((MimeMultipart) message.getContent()).getCount()).isEqualTo(1);
}
 
Example 3
Source Project: mnIMAPSync   Source File: FolderCrawlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void run_notEmptyFolderAndRepeatedMessages_shouldUpdateIndexes() throws Exception {
  // Given
  final FolderCrawler folderCrawler = new FolderCrawler(
      imapStore, "FolderName", 0, 100, index);
  final IMAPMessage message = Mockito.mock(IMAPMessage.class);
  doReturn(new String[]{"1337"}).when(message).getHeader("Message-Id");
  final IMAPMessage repeatedMessage = Mockito.mock(IMAPMessage.class);
  doReturn(new String[]{"313373"}).when(repeatedMessage).getHeader("Message-Id");
  index.getFolderMessages("FolderName").add(new MessageId(repeatedMessage));
  doReturn(new Message[]{message, repeatedMessage}).when(folder).getMessages(eq(0), eq(100));
  // When
  folderCrawler.run();
  // Then
  verify(imapStore, times(1)).getFolder(eq("FolderName"));
  assertThat(index.getIndexedMessageCount(), equalTo(1L));
  assertThat(index.getSkippedMessageCount(), equalTo(1L));
}
 
Example 4
Source Project: appengine-tck   Source File: MailServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertSenderUnauthorized(String unauthorizedSender) throws IOException {
    MimeProperties mp = new MimeProperties();
    mp.subject = "Test-Unauthorized-Sender-" + System.currentTimeMillis();
    mp.from = unauthorizedSender;
    mp.to = getEmail("to-unauthorized-sender-test", EmailMessageField.TO);
    mp.body = BODY;

    MailService.Message msg = new MailService.Message();
    msg.setSubject(mp.subject);
    msg.setSender(mp.from);
    msg.setTo(mp.to);
    msg.setTextBody(BODY);

    try {
        mailService.send(msg);
        fail("Expected IllegalArgumentException with message \"Unauthorized Sender\"");
    } catch (IllegalArgumentException e) {
        assertTrue("Expected IllegalArgumentException to contain \"Unauthorized Sender\"", e.getMessage().contains("Unauthorized Sender"));
    }
}
 
Example 5
Source Project: camunda-bpm-mail   Source File: PollMailResponse.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void collectResponseParameters(Map<String, Object> responseParameters) {

  List<Mail> mails = new ArrayList<Mail>();
  for (Message message : messages) {

    try {
      Mail mail = Mail.from(message);
      if (downloadAttachments) {
        mail.downloadAttachments(attachmentPath);
      }

      mails.add(mail);

    } catch (Exception e) {
      LOGGER.error("exception while transforming message to dto", e);
    }
  }

  responseParameters.put(PARAM_MAILS, mails);

  mailService.flush();
}
 
Example 6
Source Project: scipio-erp   Source File: MimeMessageWrapper.java    License: Apache License 2.0 6 votes vote down vote up
protected String getContentText(Object content) {
    if (content == null) {
        return null;
    }
    if (content instanceof String) {
        return (String) content;
    } else if (content instanceof InputStream) {
        return getTextFromStream((InputStream) content);
    } else if (content instanceof Message) {
        try {
            return getTextFromStream(((Message) content).getInputStream());
        } catch (Exception e) {
            Debug.logError(e, module);
            return null;
        }
    } else {
        Debug.logWarning("Content was not a string or a stream; no known handler -- " + content.toString(), module);
        return null;
    }
}
 
Example 7
Source Project: spring4-understanding   Source File: JavaMailSenderTests.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void sendMessage(Message message, Address[] addresses) throws MessagingException {
	if ("fail".equals(message.getSubject())) {
		throw new MessagingException("failed");
	}
	if (!ObjectUtils.nullSafeEquals(addresses, message.getAllRecipients())) {
		throw new MessagingException("addresses not correct");
	}
	if (message.getSentDate() == null) {
		throw new MessagingException("No sentDate specified");
	}
	if (message.getSubject() != null && message.getSubject().contains("custom")) {
		assertEquals(new GregorianCalendar(2005, 3, 1).getTime(), message.getSentDate());
	}
	this.sentMessages.add(message);
}
 
Example 8
Source Project: greenmail   Source File: Pop3ServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRetrieve() throws Exception {
    assertNotNull(greenMail.getPop3());
    final String subject = GreenMailUtil.random();
    final String body = GreenMailUtil.random() + "\r\n" + GreenMailUtil.random() + "\r\n" + GreenMailUtil.random();
    String to = "[email protected]";
    GreenMailUtil.sendTextEmailTest(to, "[email protected]", subject, body);
    greenMail.waitForIncomingEmail(5000, 1);

    try (Retriever retriever = new Retriever(greenMail.getPop3())) {
        Message[] messages = retriever.getMessages(to);
        assertEquals(1, messages.length);
        assertEquals(subject, messages[0].getSubject());
        assertEquals(body, GreenMailUtil.getBody(messages[0]).trim());

        // UID
        POP3Folder f = (POP3Folder) messages[0].getFolder();
        assertNotEquals("UNKNOWN", f.getUID(messages[0]));
    }
}
 
Example 9
Source Project: java-technology-stack   Source File: JavaMailSenderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void javaMailSenderWithMimeMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	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(mimeMessage, sender.transport.getSentMessage(0));
}
 
Example 10
@Test
public void writeResolvedEmailTest() throws Exception {
    Alert openAlert = JvmGarbageCollectionData.getOpenAlert();
    Alert ackAlert = JvmGarbageCollectionData.ackAlert(openAlert);
    Alert resolvedAlert = JvmGarbageCollectionData.resolveAlert(ackAlert);

    Action resolvedAction = new Action(resolvedAlert.getTriggerId(), "email", "email-to-test", resolvedAlert);

    resolvedAction.setProperties(properties);
    ActionMessage resolvedMessage = new TestActionMessage(resolvedAction);

    Message email = plugin.createMimeMessage(resolvedMessage);
    assertNotNull(email);
    writeEmailFile(email, this.getClass().getSimpleName() + "-3-resolved.eml");

    plugin.process(resolvedMessage);
    // Test generates 2 messages on the mail server
    assertEquals(2, server.getReceivedMessages().length);
}
 
Example 11
Source Project: EasyML   Source File: JavaMail.java    License: Apache License 2.0 6 votes vote down vote up
public boolean sendMsg(String recipient, String subject, String content)
		throws MessagingException {
	// Create a mail object
	Session session = Session.getInstance(props, new Authenticator() {
		// Set the account information session,transport will send mail
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(Constants.MAIL_USERNAME, Constants.MAIL_PASSWORD);
		}
	});
	session.setDebug(true);
	Message msg = new MimeMessage(session);
	try {
		msg.setSubject(subject);			//Set the mail subject
		msg.setContent(content,"text/html;charset=utf-8");
		msg.setFrom(new InternetAddress(Constants.MAIL_USERNAME));			//Set the sender
		msg.setRecipient(RecipientType.TO, new InternetAddress(recipient));	//Set the recipient
		Transport.send(msg);
		return true;
	} catch (Exception ex) {
		ex.printStackTrace();
		System.out.println(ex.getMessage());
		return false;
	}

}
 
Example 12
Source Project: appengine-tck   Source File: MailServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAllowedHeaders() throws Exception {
    assumeEnvironment(Environment.APPSPOT, Environment.CAPEDWARF);

    MimeProperties mp = new MimeProperties();
    mp.subject = "Allowed-Headers-Test-" + System.currentTimeMillis();
    mp.from = getEmail("from-test-header", EmailMessageField.FROM);
    mp.to = getEmail("to-test-header", EmailMessageField.TO);
    mp.body = BODY;

    MailService.Message msg = createMailServiceMessage(mp);
    msg.setTextBody(BODY);

    // https://developers.google.com/appengine/docs/java/mail/#Sending_Mail_with_Headers
    Set<MailService.Header> headers = new HashSet<>();
    Map<String, String> headersMap = createExpectedHeaders();

    for (Map.Entry entry : headersMap.entrySet()) {
        headers.add(new MailService.Header(entry.getKey().toString(), entry.getValue().toString()));
    }
    msg.setHeaders(headers);
    mailService.send(msg);

    MimeProperties receivedMp = pollForMatchingMail(mp);
    assertHeadersExist(receivedMp, createExpectedHeadersVerifyList(headersMap));
}
 
Example 13
Source Project: camunda-bpm-mail   Source File: Mail.java    License: Apache License 2.0 6 votes vote down vote up
public static Mail from(Message message) throws MessagingException, IOException {
  Mail mail = new Mail();

  mail.from = InternetAddress.toString(message.getFrom());
  mail.to =  InternetAddress.toString(message.getRecipients(RecipientType.TO));
  mail.cc = InternetAddress.toString(message.getRecipients(RecipientType.CC));

  mail.subject = message.getSubject();
  mail.sentDate = message.getSentDate();
  mail.receivedDate = message.getReceivedDate();

  mail.messageNumber = message.getMessageNumber();

  if (message instanceof MimeMessage) {
    MimeMessage mimeMessage = (MimeMessage) message;
    // extract more informations
    mail.messageId = mimeMessage.getMessageID();
  }

  processMessageContent(message, mail);

  return mail;
}
 
Example 14
Source Project: translationstudio8   Source File: MailUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
 * @param message
 *            邮件对象
 * @throws MessagingException
 *             the messaging exception
 */
public static void removeDumplicate(Message message) throws MessagingException {
	Address[] from = message.getFrom();
	Address[] to = message.getRecipients(Message.RecipientType.TO);
	Address[] cc = message.getRecipients(Message.RecipientType.CC);
	Address[] bcc = message.getRecipients(Message.RecipientType.BCC);
	Address[] tonew = removeDuplicate(from, to);
	Address[] ccnew = removeDuplicate(from, cc);
	Address[] bccnew = removeDuplicate(from, bcc);
	if (tonew != null) {
		message.setRecipients(Message.RecipientType.TO, tonew);
	}
	if (ccnew != null) {
		message.setRecipients(Message.RecipientType.CC, ccnew);
	}
	if (bccnew != null) {
		message.setRecipients(Message.RecipientType.BCC, bccnew);
	}
}
 
Example 15
Source Project: chipster   Source File: Emails.java    License: MIT License 6 votes vote down vote up
/**
 * Send a regular email.
 * 
 * @param toEmail receiver's email
 * @param replyTo email for reply or null
 * @param subject
 * @param body
 */
public static void sendEmail(String toEmail, String replyTo, String subject, String body) {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage message = new MimeMessage(session);
    try {
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
        message.setSubject(subject);
        message.setText(body);
        
        // set email for reply
        if (replyTo != null) {
            message.addHeader("Reply-To", replyTo);
        }
        
        Transport.send(message);
    } catch (MessagingException e){
        System.err.println("Email could not be sent.");
    }
}
 
Example 16
Source Project: chronos   Source File: SendMail.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@CoverageIgnore
public static void doSend(String subject, String messageBody, MailInfo mailInfo, Session session) {
  String hostname = "";
  try {
    hostname = InetAddress.getLocalHost().getHostName();
  } catch (Exception ignore) {}
  
  try {
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(mailInfo.from, mailInfo.fromName + " " + hostname));
    for (String currTo : mailInfo.to.split(",")) {
      msg.addRecipient(Message.RecipientType.TO,
                       new InternetAddress(currTo, mailInfo.toName));
    }
    msg.setSubject(subject);
    msg.setContent(messageBody, "text/html");
    Transport.send(msg);
    
  } catch (UnsupportedEncodingException | MessagingException e) {
    LOG.error("SendMail error:", e);
  }
  LOG.info(String.format("Sent email from %s, to %s", mailInfo.from, mailInfo.to));
}
 
Example 17
Source Project: FairEmail   Source File: YoungerTerm.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
    * The match method.
    *
    * @param msg	the date comparator is applied to this Message's
    *			received date
    * @return		true if the comparison succeeds, otherwise false
    */
   @Override
   public boolean match(Message msg) {
Date d;

try {
    d = msg.getReceivedDate();
} catch (Exception e) {
    return false;
}

if (d == null)
    return false;

return d.getTime() >=
	    System.currentTimeMillis() - ((long)interval * 1000);
   }
 
Example 18
Source Project: java-course-ee   Source File: ComposeSimpleMessage.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        final Properties props = new Properties();
        props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(props.getProperty("smtp.username"), props.getProperty("smtp.pass"));
            }
        });

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(props.getProperty("address.sender")));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
        message.setSubject("Test JavaMail");

        message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");

        Transport.send(message);

        log.info("Message was sent");
    }
 
Example 19
Source Project: hawkular-alerts   Source File: UrlAvailabilityEmailTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void writeResolvedEmailTest() throws Exception {
    Alert openAlert = UrlAvailabilityData.getOpenAlert();
    Alert ackAlert = UrlAvailabilityData.ackAlert(openAlert);
    Alert resolvedAlert = UrlAvailabilityData.resolveAlert(ackAlert);

    Action resolvedAction = new Action(resolvedAlert.getTriggerId(), "email", "email-to-test", resolvedAlert);

    resolvedAction.setProperties(properties);
    ActionMessage resolvedMessage = new TestActionMessage(resolvedAction);

    Message email = plugin.createMimeMessage(resolvedMessage);
    assertNotNull(email);
    writeEmailFile(email, this.getClass().getSimpleName() + "-3-resolved.eml");

    plugin.process(resolvedMessage);
    // Test generates 2 messages on the mail server
    assertEquals(2, server.getReceivedMessages().length);
}
 
Example 20
@Test
public void shouldIgnoreNullCc() throws Exception {
    //Arrange
    when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));

    final DefaultEmail email = DefaultEmail.builder()
            .from(getCiceroMainMailAddress())
            .replyTo(getCiceroSecondayMailAddress())
            .to(Lists.newArrayList(new InternetAddress("[email protected]", "[email protected]", "Pomponius Attĭcus")))
            .bcc(Lists.newArrayList(new InternetAddress("[email protected]", "Caius Memmius")))
            .depositionNotificationTo(new InternetAddress("[email protected]", "Gaius Iulius Caesar Augustus Germanicus"))
            .receiptTo(new InternetAddress("[email protected]", "Gaius Iulius Caesar Augustus Germanicus"))
            .subject("Laelius de amicitia")
            .body("Firmamentum autem stabilitatis constantiaeque eius, quam in amicitia quaerimus, fides est.")
            .customHeaders(CUSTOM_HEADERS)
            .build();


    //Act
    MimeMessage message = emailToMimeMessage.apply(email);

    //Assert
    assertions.assertThat(message.getRecipients(Message.RecipientType.CC)).isNullOrEmpty();
}
 
Example 21
Source Project: FairEmail   Source File: MessageIDTerm.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
    * The match method.
    *
    * @param msg	the match is applied to this Message's 
    *			Message-ID header
    * @return		true if the match succeeds, otherwise false
    */
   @Override
   public boolean match(Message msg) {
String[] s;

try {
    s = msg.getHeader("Message-ID");
} catch (Exception e) {
    return false;
}

if (s == null)
    return false;

for (int i=0; i < s.length; i++)
    if (super.match(s[i]))
	return true;
return false;
   }
 
Example 22
Source Project: javamail   Source File: AbstractFileTransportTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws MessagingException, IOException {
    Properties properties = new Properties();
    properties.put("mail.files.path", "target" + File.separatorChar + "output");
    Session session = Session.getDefaultInstance(properties);
    transport = new AbstractFileTransport(session, new URLName("AbstractFileDev")) {
        @Override
        protected void writeMessage(Message message, OutputStream os) throws IOException, MessagingException {
            // do nothing
        }
        @Override
        protected String getFilenameExtension() {
            return BASE_EXT;
        }
    };
    cleanup();
}
 
Example 23
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount,
        final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}
 
Example 24
private static void sendMail()
        throws MessagingException, IOException {
    Session session = Session.getInstance(getMailProps(), new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    getVal("username"),
                    getVal("password"));
        }
    });
    session.setDebug(getBoolVal("mail.debug"));
    LOG.info("Compiling Mail before Sending");
    Message message = createMessage(session);
    Transport transport = session.getTransport("smtp");
    LOG.info("Connecting to Mail Server");
    transport.connect();
    LOG.info("Sending Mail");
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    LOG.info("Reports are sent to Mail");
    clearTempZips();
}
 
Example 25
Source Project: javamail-mock2   Source File: IMAPMockFolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void copyMessages(final Message[] msgs, final Folder folder) throws MessagingException {
    abortIdle();
    checkOpened();
    checkExists();
    if (msgs == null || folder == null || msgs.length == 0) {
        return;
    }

    if (!folder.exists()) {
        throw new FolderNotFoundException(folder.getFullName() + " does not exist", folder);
    }

    folder.appendMessages(msgs);
}
 
Example 26
Source Project: qaf   Source File: MalinatorUtil.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		Properties props = new Properties();

		String host = "pop.mailinator.com";
		String username = "x-test-m";
		String password = "mypwdxxx";
		String provider = "pop3";

		Session session = Session.getDefaultInstance(props, null);
		Store store = session.getStore(provider);
		store.connect(host, username, password);

		Folder inbox = store.getFolder("INBOX");
		if (inbox == null) {
			System.out.println("No INBOX");
			System.exit(1);
		}
		inbox.open(Folder.READ_ONLY);

		Message[] messages = inbox.getMessages();
		for (int i = 0; i < messages.length; i++) {
			System.out.println("Message " + (i + 1));
			messages[i].writeTo(System.out);
		}
		inbox.close(false);
		store.close();

	}
 
Example 27
private void send(String to, String subj, String body, String contentType) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subj, "UTF-8");
    message.setContent(body, contentType);

    try (Transport transport = session.getTransport()) {
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
    }

    log.debug("Mail sent to {}. Subj: {}", to, subj);
    log.trace("Mail body: {}", body);
}
 
Example 28
private Message fetchMail(String loginId, String password) throws MessagingException, InterruptedException {
	ImapServer imapd = mailMock.getImap();
	Message msg = null;
	while ((msg = retrieveViaImap(imapd.getBindTo(), imapd.getPort(), loginId, password)) == null) {
		MILLISECONDS.sleep(100);
	}
	return msg;
}
 
Example 29
Source Project: spring-analysis-note   Source File: JavaMailSenderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void javaMailProperties() throws MessagingException {
	Properties props = new Properties();
	props.setProperty("bogusKey", "bogusValue");
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals("bogusValue", sess.getProperty("bogusKey"));
			return super.getTransport(sess);
		}
	};
	sender.setJavaMailProperties(props);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	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(mimeMessage, sender.transport.getSentMessage(0));
}
 
Example 30
Source Project: blackduck-alert   Source File: EmailMessagingService.java    License: Apache License 2.0 5 votes vote down vote up
public void sendMessages(EmailProperties emailProperties, Session session, List<Message> messages) throws AlertException {
    Set<String> errorMessages = new HashSet<>();
    Set<String> invalidRecipients = new HashSet<>();
    for (Message message : messages) {
        Address[] recipients = null;
        try {
            recipients = message.getAllRecipients();
            if (Boolean.valueOf(emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_AUTH_KEY))) {
                sendAuthenticated(emailProperties, message, session);
            } else {
                Transport.send(message);
            }
        } catch (MessagingException e) {
            if (recipients != null) {
                Stream.of(recipients).map(Address::toString).forEach(invalidRecipients::add);
            }
            errorMessages.add(e.getMessage());
            logger.error("Could not send this email to the following recipients: {}. Reason: {}", recipients, e.getMessage());
        }
    }
    if (!errorMessages.isEmpty()) {
        String errorMessage;
        if (invalidRecipients.isEmpty()) {
            errorMessage = "Errors sending emails. " + StringUtils.join(errorMessages, ", ");
        } else {
            errorMessage = "Error sending emails to the following recipients: " + invalidRecipients;
        }
        throw new AlertException(errorMessage);
    }
}