javax.mail.Message Java Examples

The following examples show how to use javax.mail.Message. 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: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: MimeMessageWrapper.java    From scipio-erp with 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 #3
Source File: EmailService.java    From fido2 with 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 #4
Source File: PollMailResponse.java    From camunda-bpm-mail with 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 #5
Source File: FolderCrawlerTest.java    From mnIMAPSync with 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 #6
Source File: MailServiceTest.java    From appengine-tck with 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 #7
Source File: JavaMailSenderTests.java    From spring4-understanding with 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 File: Pop3ServerTest.java    From greenmail with 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 File: JavaMailSenderTests.java    From java-technology-stack with 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
Source File: JvmGarbageCollectionEmailTest.java    From hawkular-alerts with Apache License 2.0 6 votes vote down vote up
@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 File: JavaMail.java    From EasyML with 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 File: MailServiceTest.java    From appengine-tck with 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 File: MailUtils.java    From translationstudio8 with 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 #14
Source File: SendEmailServiceTest.java    From nomulus with 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 #15
Source File: AbstractIMAPRiverUnitTest.java    From elasticsearch-imap with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: AbstractFileTransportTest.java    From javamail with 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 #17
Source File: MessageIDTerm.java    From FairEmail with 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 #18
Source File: EmailToMimeMessageTest.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: UrlAvailabilityEmailTest.java    From hawkular-alerts with 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
Source File: ComposeSimpleMessage.java    From java-course-ee with 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 #21
Source File: YoungerTerm.java    From FairEmail with 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 #22
Source File: SendMail.java    From chronos with 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 #23
Source File: Emails.java    From chipster with 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 #24
Source File: Mail.java    From camunda-bpm-mail with 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 #25
Source File: MimeFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the last modified time of this file.
 */
@Override
protected long doGetLastModifiedTime() throws Exception {
    final Message mm = getMessage();
    if (mm == null) {
        return -1;
    }
    if (mm.getSentDate() != null) {
        return mm.getSentDate().getTime();
    }
    if (mm.getReceivedDate() != null) {
        mm.getReceivedDate();
    }
    return 0;
}
 
Example #26
Source File: MailService.java    From commafeed with Apache License 2.0 5 votes vote down vote up
public void sendMail(User user, String subject, String content) throws Exception {

		ApplicationSettings settings = config.getApplicationSettings();

		final String username = settings.getSmtpUserName();
		final String password = settings.getSmtpPassword();
		final String fromAddress = Optional.ofNullable(settings.getSmtpFromAddress()).orElse(settings.getSmtpUserName());

		String dest = user.getEmail();

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "" + settings.isSmtpTls());
		props.put("mail.smtp.host", settings.getSmtpHost());
		props.put("mail.smtp.port", "" + settings.getSmtpPort());

		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(fromAddress, "CommaFeed"));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(dest));
		message.setSubject("CommaFeed - " + subject);
		message.setContent(content, "text/html; charset=utf-8");

		Transport.send(message);

	}
 
Example #27
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void fFailedMimeMessage() throws Exception {
	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 #28
Source File: ThirdPartyMailClient.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
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 #29
Source File: AssertEmail.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static void assertRecipients(List<String> expectedRecipients, Message actualEmail, RecipientType recipientType, AssertionRegistry assertions) throws MessagingException {
	Address[] actualRecipients = actualEmail == null ? null : actualEmail.getRecipients(recipientType);
	if (expectedRecipients.isEmpty()) {
		assertions.register(() -> Assert.assertTrue("should be received by no recipients (of type RecipientType." + recipientType + ")", actualRecipients == null || actualRecipients.length == 0));
	} else {
		assertions.register(() -> Assert.assertEquals("should be received by " + expectedRecipients.size() + " recipients (of type RecipientType." + recipientType + ")",
				(Integer) expectedRecipients.size(), actualRecipients == null ? null : actualRecipients.length));
		for (int i = 0; i < expectedRecipients.size(); i++) {
			final int idx = i;
			assertions.register(() -> Assert.assertEquals("recipient " + recipientType + "[" + idx + "] should be '" + expectedRecipients.get(idx) + "'", expectedRecipients.get(idx),
					actualRecipients != null && idx < actualRecipients.length ? actualRecipients[idx].toString() : null));
		}
	}
}
 
Example #30
Source File: GmailThrIdTerm.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
/**
    * The match method.
    *
    * @param msg	the Message number is matched with this Message
    * @return		true if the match succeeds, otherwise false
    */
   public boolean match(Message msg) {
long thrId;

try {
    if (msg instanceof GmailMessage)
	thrId = ((GmailMessage)msg).getThrId();
    else
	return false;
} catch (Exception e) {
    return false;
}

return super.match(thrId);
   }