javax.mail.Message.RecipientType Java Examples

The following examples show how to use javax.mail.Message.RecipientType. 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: MailboxFolderTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddMessages() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg);

    Assert.assertEquals(1, mf.getMessageCount());
    Assert.assertNotNull(mf.getByMsgNum(1));
    Assert.assertEquals(msg.getSubject(), mf.getByMsgNum(1).getSubject());

    mf.add(msg);
    mf.add(msg);
    Assert.assertEquals(3, mf.getMessageCount());
    Assert.assertNotNull(mf.getByMsgNum(3));
    Assert.assertEquals(msg.getSubject(), mf.getByMsgNum(3).getSubject());

}
 
Example #2
Source File: SMTPTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test3SendMessage() throws Exception {

    Session.getDefaultInstance(getProperties());

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test 1");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    Transport.send(msg);

    final Store store = session.getStore("mock_pop3");
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(1, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));
    Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
    inbox.close(false);

}
 
Example #3
Source File: SpitterMailServiceImplTest.java    From Project with Apache License 2.0 6 votes vote down vote up
@Test
public void sendSimpleSpittleEmail() throws Exception {
	Spitter spitter = new Spitter(1L, "habuma", null, "Craig Walls", "[email protected]", true);
	Spittle spittle = new Spittle(1L, spitter, "Hiya!", new Date());
	mailService.sendSimpleSpittleEmail("[email protected]", spittle);

	MimeMessage[] receivedMessages = mailServer.getReceivedMessages();
	assertEquals(1, receivedMessages.length);
	assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject());
	assertEquals("Craig Walls says: Hiya!", ((String) receivedMessages[0].getContent()).trim());
	Address[] from = receivedMessages[0].getFrom();
	assertEquals(1, from.length);
	assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress());
	assertEquals("[email protected]",
			((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress());
}
 
Example #4
Source File: SpitterMailServiceImplTest.java    From Project with Apache License 2.0 6 votes vote down vote up
public void receiveTest() throws Exception {
	MimeMessage[] receivedMessages = mailServer.getReceivedMessages();
	assertEquals(1, receivedMessages.length);
	assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject());
	Address[] from = receivedMessages[0].getFrom();
	assertEquals(1, from.length);
	assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress());
	assertEquals(toEmail,
			((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress());

	MimeMultipart multipart = (MimeMultipart) receivedMessages[0].getContent();
	Part part = null;
	for(int i=0;i<multipart.getCount();i++) {
		part = multipart.getBodyPart(i);
		System.out.println(part.getFileName());
		System.out.println(part.getSize());
	}
}
 
Example #5
Source File: SmtpMail.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void send() {

    try {
        Address[] addrs = message.getRecipients(RecipientType.TO);
        if (addrs == null || addrs.length == 0) {
            log.warn("Aborting mail message " + message.getSubject() +
                    ": No recipients");
            return;
        }
        Transport.send(message);
    }
    catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " +
                             me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}
 
Example #6
Source File: SmtpMail.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Private helper method to do the heavy lifting of setting the recipients field for
 * a message
 * @param type The javax.mail.Message.RecipientType (To, CC, or BCC) for the recipients
 * @param recipIn A string array of email addresses
 */
private void setRecipients(RecipientType type, String[] recipIn) {
    log.debug("setRecipients called.");
    Address[] recAddr = null;
    try {
        List tmp = new LinkedList();
        for (int i = 0; i < recipIn.length; i++) {
            InternetAddress addr = new InternetAddress(recipIn[i]);
            log.debug("checking: " + addr.getAddress());
            if (verifyAddress(addr)) {
                log.debug("Address verified.  Adding: " + addr.getAddress());
                tmp.add(addr);
            }
        }
        recAddr = new Address[tmp.size()];
        tmp.toArray(recAddr);
        message.setRecipients(type, recAddr);
    }
    catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " +
                            me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}
 
Example #7
Source File: SmtpMail.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void send() {

    try {
        Address[] addrs = message.getRecipients(RecipientType.TO);
        if (addrs == null || addrs.length == 0) {
            log.warn("Aborting mail message " + message.getSubject() +
                    ": No recipients");
            return;
        }
        Transport.send(message);
    }
    catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " +
                             me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}
 
Example #8
Source File: SmtpMail.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Private helper method to do the heavy lifting of setting the recipients field for
 * a message
 * @param type The javax.mail.Message.RecipientType (To, CC, or BCC) for the recipients
 * @param recipIn A string array of email addresses
 */
private void setRecipients(RecipientType type, String[] recipIn) {
    log.debug("setRecipients called.");
    Address[] recAddr = null;
    try {
        List tmp = new LinkedList();
        for (int i = 0; i < recipIn.length; i++) {
            InternetAddress addr = new InternetAddress(recipIn[i]);
            log.debug("checking: " + addr.getAddress());
            if (verifyAddress(addr)) {
                log.debug("Address verified.  Adding: " + addr.getAddress());
                tmp.add(addr);
            }
        }
        recAddr = new Address[tmp.size()];
        tmp.toArray(recAddr);
        message.setRecipients(type, recAddr);
    }
    catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " +
                            me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}
 
Example #9
Source File: EMailTestServer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void deliverMultipartMessage(String user, String password, String from, String subject,
                                                                   String contentType, Object body) throws Exception {
    GreenMailUser greenUser = greenMail.setUser(user, password);
    MimeMultipart multiPart = new MimeMultipart();
    MimeBodyPart textPart = new MimeBodyPart();
    multiPart.addBodyPart(textPart);
    textPart.setContent(body, contentType);

    Session session = GreenMailUtil.getSession(server.getServerSetup());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setRecipients(Message.RecipientType.TO, greenUser.getEmail());
    mimeMessage.setFrom(from);
    mimeMessage.setSubject(subject);
    mimeMessage.setContent(multiPart, "multipart/mixed");
    greenUser.deliver(mimeMessage);
}
 
Example #10
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 #11
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 #12
Source File: SMTPTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test2SendMessage2() throws Exception {

    final Transport transport = session.getTransport(Providers.getSMTPProvider("makes_no_difference_here", true, true));

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test 1");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    transport.sendMessage(msg, new Address[] { new InternetAddress("[email protected]") });

    final Store store = session.getStore("mock_pop3");
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(1, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));
    Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
    inbox.close(false);

}
 
Example #13
Source File: SendMailConnector.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
protected Message createMessage(SendMailRequest request, Session session) throws Exception {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(request.getFrom(), request.getFromAlias()));
    message.setRecipients(RecipientType.TO, InternetAddress.parse(request.getTo()));

    if (request.getCc() != null) {
      message.setRecipients(RecipientType.CC, InternetAddress.parse(request.getCc()));
    }
    if (request.getBcc() != null) {
      message.setRecipients(RecipientType.BCC, InternetAddress.parse(request.getBcc()));
    }

    message.setSentDate(new Date());
    message.setSubject(request.getSubject());

    if (hasContent(request)) {
      createMessageContent(message, request);
    } else {
      message.setText("");
    }

    return message;
  }
 
Example #14
Source File: SendMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void messageWithCc() throws MessagingException {

 MailConnectors.sendMail()
    .createRequest()
      .from("test")
      .to("[email protected]")
      .cc("[email protected]")
      .subject("subject")
    .execute();

  MimeMessage[] mails = greenMail.getReceivedMessages();
  assertThat(mails).hasSize(2);

  assertThat(mails[0].getRecipients(RecipientType.CC))
    .hasSize(1)
    .extracting("address").contains("[email protected]");
}
 
Example #15
Source File: SendMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void messageWithBcc() throws MessagingException {

 MailConnectors.sendMail()
    .createRequest()
      .from("test")
      .to("[email protected]")
      .bcc("[email protected]")
      .subject("subject")
    .execute();

  MimeMessage[] mails = greenMail.getReceivedMessages();
  assertThat(mails).hasSize(2);

  assertThat(mails[0].getRecipients(RecipientType.TO))
    .hasSize(1)
    .extracting("address").contains("[email protected]");

  assertThat(mails[0].getRecipients(RecipientType.BCC)).isNull();
}
 
Example #16
Source File: MailboxFolderTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUIDMessages() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg);
    mf.add(msg);
    mf.add(msg);

    Assert.assertTrue(mf.getUID(mf.getByMsgNum(3)) > 0);
    Assert.assertNotNull(mf.getById(mf.getUID(mf.getByMsgNum(3))));

}
 
Example #17
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 #18
Source File: SendEmailServiceTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_bcc() throws Exception {
  EmailMessage content =
      createBuilder()
          .setBccs(
              ImmutableList.of(
                  new InternetAddress("[email protected]"),
                  new InternetAddress("[email protected]")))
          .build();
  sendEmailService.sendEmail(content);
  Message message = getMessage();
  assertThat(message.getRecipients(RecipientType.BCC))
      .asList()
      .containsExactly(
          new InternetAddress("[email protected]"), new InternetAddress("[email protected]"));
}
 
Example #19
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Address message.
 *
 * @param msg message, may not be null.
 * @throws MessagingException thrown if error addressing message.
 */
private final void addressMessage(final Message msg) throws MessagingException {

   if (from != null) {
      msg.setFrom(getAddress(from));
   } else {
      msg.setFrom();
   }

   if (to != null && !to.isEmpty()) {
      msg.setRecipients(RecipientType.TO, parseAddress(to));
   }

   //Add CC recipients if defined.
   if (cc != null && !cc.isEmpty()) {
      msg.setRecipients(RecipientType.CC, parseAddress(cc));
   }

   //Add BCC recipients if defined.
   if (bcc != null && !bcc.isEmpty()) {
      msg.setRecipients(RecipientType.BCC, parseAddress(bcc));
   }
}
 
Example #20
Source File: MailboxFolderTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test(expected = MockTestException.class)
public void testMockMessagesReadonly() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg);

    try {
        mf.getByMsgNum(1).setHeader("test", "test");
    } catch (final IllegalWriteException e) {
        throw new MockTestException(e);
    }

}
 
Example #21
Source File: Email.java    From smslib-v3 with Apache License 2.0 6 votes vote down vote up
@Override
public void MessagesReceived(Collection<InboundMessage> msgList) throws Exception
{
	for (InboundMessage im : msgList)
	{
		Message msg = new MimeMessage(this.mailSession);
		msg.setFrom();
		msg.addRecipient(RecipientType.TO, new InternetAddress(getProperty("to")));
		msg.setSubject(updateTemplateString(this.messageSubject, im));
		if (this.messageBody != null)
		{
			msg.setText(updateTemplateString(this.messageBody, im));
		}
		else
		{
			msg.setText(im.toString());
		}
		msg.setSentDate(im.getDate());
		Transport.send(msg);
	}
}
 
Example #22
Source File: MailManager.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Add recipient addresses to the e-mail.
 * @param msg The mime message to which add the addresses.
 * @param recType The specific recipient type to which add the addresses.
 * @param recipients The recipient addresses.
 */
protected void addRecipients(MimeMessage msg, RecipientType recType, String[] recipients) {
	if (null != recipients) {
		try {
			Address[] addresses = new Address[recipients.length];
			for (int i = 0; i < recipients.length; i++) {
				Address address = new InternetAddress(recipients[i]);
				addresses[i] = address;
			}
			msg.setRecipients(recType, addresses);
		} catch (MessagingException e) {
			throw new RuntimeException("Error adding recipients", e);
		}
	}
}
 
Example #23
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddMessages() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13

    final Store store = session.getStore();
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

    Assert.assertEquals(3, inbox.getMessageCount());

    inbox.open(Folder.READ_WRITE);
    inbox.getMessage(1).setFlag(Flag.DELETED, true);

    inbox.close(true);

    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof UIDFolder);
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(12L, ((UIDFolder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example #24
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testACLUnsupported() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore("mock_imap");
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder test = defaultFolder.getFolder("test");

    final IMAPFolder testImap = (IMAPFolder) test;

    try {
        testImap.getACL();
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example #25
Source File: POP3TestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testOnlyInbox() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore(Providers.getPOP3Provider("makes_no_differernce", false, true));
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();

    try {
        defaultFolder.getFolder("test");
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example #26
Source File: POP3TestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddMessages() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13

    final Store store = session.getStore();
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

    Assert.assertEquals(3, inbox.getMessageCount());

    inbox.open(Folder.READ_ONLY);
    inbox.getMessage(1).setFlag(Flag.DELETED, true);

    inbox.close(true);
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof POP3Folder);
    Assert.assertEquals("12", ((POP3Folder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example #27
Source File: DefaultStaticDependenciesDelegator.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public MimeMessage createMessage(InternetAddress from, List<? extends ContactList> listOfContactLists, String body, String subject, File[] attachments, MailerResult result)  throws AddressException, MessagingException {
	MimeMessage tmpMessage = MailHelper.createMessage();
	for (ContactList tmp : listOfContactLists) {
		InternetAddress groupName[] = InternetAddress.parse(tmp.getRFC2822Name() + ";");
		InternetAddress members[] = tmp.getEmailsAsAddresses();
		tmpMessage.addRecipients(RecipientType.TO, groupName);
		tmpMessage.addRecipients(RecipientType.BCC, members);
	}
	Address recipients[] = tmpMessage.getRecipients(RecipientType.TO);
	Address recipientsBCC[] = tmpMessage.getRecipients(RecipientType.BCC);
	
	return createMessage(from, recipients, null, recipientsBCC, body, subject, attachments, result);
}
 
Example #28
Source File: ForgotPasswordCommand.java    From FlexibleLogin with MIT License 5 votes vote down vote up
private MimeMessage buildMessage(User player, String email, String newPassword, MailConfig emailConfig,
                                 Session session) throws MessagingException, UnsupportedEncodingException {
    String serverName = Sponge.getServer().getBoundAddress()
            .map(sa -> sa.getAddress().getHostAddress())
            .orElse("Minecraft Server");
    ImmutableMap<String, String> variables = ImmutableMap.of("player", player.getName(),
            "server", serverName,
            "password", newPassword);

    MimeMessage message = new MimeMessage(session);
    String senderEmail = emailConfig.getAccount();

    //sender email with an alias
    message.setFrom(new InternetAddress(senderEmail, emailConfig.getSenderName()));
    message.setRecipient(RecipientType.TO, new InternetAddress(email, player.getName()));
    message.setSubject(emailConfig.getSubject(serverName, player.getName()).toPlain());

    //current time
    message.setSentDate(Calendar.getInstance().getTime());
    String textContent = emailConfig.getText(serverName, player.getName(), newPassword).toPlain();

    //html part
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(textContent, "text/html; charset=UTF-8");

    //plain text
    BodyPart textPart = new MimeBodyPart();
    textPart.setContent(textContent.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " "), "text/plain; charset=UTF-8");

    Multipart alternative = new MimeMultipart("alternative");
    alternative.addBodyPart(htmlPart);
    alternative.addBodyPart(textPart);
    message.setContent(alternative);
    return message;
}
 
Example #29
Source File: ContactExtractor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Stream<String> getRecipients(MimeMessage mimeMessage, RecipientType recipientType) throws MessagingException {
    boolean notStrict = false;
    Function<String, InternetAddress[]> parseRecipient =
        Throwing.function((String header) -> InternetAddress.parseHeader(header, notStrict))
            .sneakyThrow();

    return StreamUtils.ofOptional(
        Optional.ofNullable(mimeMessage.getHeader(recipientType.toString(), ","))
            .map(parseRecipient))
        .map(Address::toString)
        .map(MimeUtil::unscrambleHeaderValue);
}
 
Example #30
Source File: ContactExtractor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private ImmutableList<String> getAllRecipients(MimeMessage mimeMessage) throws MessagingException {
    return StreamUtils
        .flatten(
            getRecipients(mimeMessage, Message.RecipientType.TO),
            getRecipients(mimeMessage, Message.RecipientType.CC),
            getRecipients(mimeMessage, Message.RecipientType.BCC))
        .collect(Guavate.toImmutableList());
}