Java Code Examples for javax.mail.internet.MimeMessage#getRecipients()

The following examples show how to use javax.mail.internet.MimeMessage#getRecipients() . 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: MessageHelper.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
private static void addAddress(String email, Message.RecipientType type, MimeMessage imessage, EntityIdentity identity) throws MessagingException {
    List<Address> result = new ArrayList<>();

    Address[] existing = imessage.getRecipients(type);
    if (existing != null)
        result.addAll(Arrays.asList(existing));

    Address[] all = imessage.getAllRecipients();
    Address[] addresses = convertAddress(InternetAddress.parse(email), identity);
    for (Address address : addresses) {
        boolean found = false;
        if (all != null)
            for (Address a : all)
                if (equalEmail(a, address)) {
                    found = true;
                    break;
                }
        if (!found)
            result.add(address);
    }

    imessage.setRecipients(type, result.toArray(new Address[0]));
}
 
Example 2
Source File: MailUtils.java    From scada with MIT License 6 votes vote down vote up
/**
 * �����ռ������ͣ���ȡ�ʼ��ռ��ˡ����ͺ����͵�ַ������ռ�������Ϊ�գ��������е��ռ���
 * <p>Message.RecipientType.TO  �ռ���</p>
 * <p>Message.RecipientType.CC  ����</p>
 * <p>Message.RecipientType.BCC ����</p>
 * @param msg �ʼ�����
 * @param type �ռ�������
 * @return �ռ���1 <�ʼ���ַ1>, �ռ���2 <�ʼ���ַ2>, ...
 */ 
public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException { 
    StringBuffer receiveAddress = new StringBuffer(); 
    Address[] addresss = null; 
    if (type == null) { 
        addresss = msg.getAllRecipients(); 
    } else { 
        addresss = msg.getRecipients(type); 
    } 
     
    if (addresss == null || addresss.length < 1) 
        throw new MessagingException("û���ռ���!"); 
    for (Address address : addresss) { 
        InternetAddress internetAddress = (InternetAddress)address; 
        receiveAddress.append(internetAddress.toUnicodeString()).append(","); 
    } 
     
    receiveAddress.deleteCharAt(receiveAddress.length()-1); //ɾ�����һ������ 
     
    return receiveAddress.toString(); 
}
 
Example 3
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for CC / BCC 
 * @throws Exception 
 */
@Test
public void testSendingToCarbonCopy() throws IOException, MessagingException
{
    // PARAM_TO variant
    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
    mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TO, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_CC, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_BCC, "[email protected]");

    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing CARBON COPY");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/test.txt.ftl");

    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) getModel());

    ACTION_SERVICE.executeAction(mailAction, null);

    MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
    Assert.assertNotNull(message);
    Address[] all = message.getAllRecipients();
    Address[] ccs = message.getRecipients(RecipientType.CC);
    Address[] bccs = message.getRecipients(RecipientType.BCC);
    Assert.assertEquals(3, all.length);
    Assert.assertEquals(1, ccs.length);
    Assert.assertEquals(1, bccs.length);
    Assert.assertTrue(ccs[0].toString().contains("some.carbon"));
    Assert.assertTrue(bccs[0].toString().contains("some.blindcarbon"));
}
 
Example 4
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * ALF-21948
 */
@Test
public void testSendingToArrayOfCarbonCopyAndBlindCarbonCopyUsers() throws MessagingException
{
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    String[] ccArray = { "[email protected]", "[email protected]" };
    String[] bccArray = { "[email protected]", "[email protected]", "[email protected]" };
    params.put(MailActionExecuter.PARAM_FROM, "[email protected]");
    params.put(MailActionExecuter.PARAM_TO, "[email protected]");
    params.put(MailActionExecuter.PARAM_CC, ccArray);
    params.put(MailActionExecuter.PARAM_BCC, bccArray);

    params.put(MailActionExecuter.PARAM_TEXT, "Mail body here");
    params.put(MailActionExecuter.PARAM_SUBJECT, "Subject text");

    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME, params);
    ACTION_EXECUTER.resetTestSentCount();

    ACTION_SERVICE.executeAction(mailAction, null);
    MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
    Assert.assertNotNull(message);

    Address[] all = message.getAllRecipients();
    Address[] ccs = message.getRecipients(RecipientType.CC);
    Address[] bccs = message.getRecipients(RecipientType.BCC);
    Assert.assertEquals(6, all.length);
    Assert.assertEquals(2, ccs.length);
    Assert.assertEquals(3, bccs.length);
    Assert.assertTrue(ccs[0].toString().contains("cc_user1") && ccs[1].toString().contains("cc_user2"));
    Assert.assertTrue(bccs[0].toString().contains("bcc_user3") && bccs[1].toString().contains("bcc_user4")
                      && bccs[2].toString().contains("bcc_user5"));
}
 
Example 5
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * ALF-21948
 */
@Test
public void testSendingToListOfCarbonCopyAndBlindCarbonCopyUsers() throws MessagingException
{
    List<String> ccList = new ArrayList<String>();
    ccList.add("[email protected]");
    ccList.add("[email protected]");

    List<String> bccList = new ArrayList<String>();
    bccList.add("[email protected]");
    bccList.add("[email protected]");
    bccList.add("[email protected]");

    Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
    mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TO, "[email protected]");
    mailAction.setParameterValue(MailActionExecuter.PARAM_CC, (Serializable) ccList);
    mailAction.setParameterValue(MailActionExecuter.PARAM_BCC, (Serializable) bccList);

    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing (BLIND) CARBON COPY");
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, "mail body here");

    ACTION_EXECUTER.resetTestSentCount();
    ACTION_SERVICE.executeAction(mailAction, null);
    MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
    Assert.assertNotNull(message);

    Address[] all = message.getAllRecipients();
    Address[] ccs = message.getRecipients(RecipientType.CC);
    Address[] bccs = message.getRecipients(RecipientType.BCC);
    Assert.assertEquals(6, all.length);
    Assert.assertEquals(2, ccs.length);
    Assert.assertEquals(3, bccs.length);
    Assert.assertTrue(ccs[0].toString().contains("cc_user1") && ccs[1].toString().contains("cc_user2"));
    Assert.assertTrue(bccs[0].toString().contains("bcc_user3") && bccs[1].toString().contains("bcc_user4")
                      && bccs[2].toString().contains("bcc_user5"));
}
 
Example 6
Source File: EmailSender.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
public final int getToCount(MimeMessage mimeMessage) throws Exception {
	if (mimeMessage != null) {
		Address[] to = mimeMessage.getRecipients(javax.mail.Message.RecipientType.TO);
		if (to != null) {
			return to.length;
		}
	}
	return 0;
}
 
Example 7
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public Address[] getTo() {
    MimeMessage message = getMessage();
    try {
        return message.getRecipients(MimeMessage.RecipientType.TO);
    } catch (MessagingException e) {
        Debug.logError(e, module);
        return null;
    }
}
 
Example 8
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public Address[] getCc() {
    MimeMessage message = getMessage();
    try {
        return message.getRecipients(MimeMessage.RecipientType.CC);
    } catch (MessagingException e) {
        Debug.logError(e, module);
        return null;
    }
}
 
Example 9
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public Address[] getBcc() {
    MimeMessage message = getMessage();
    try {
        return message.getRecipients(MimeMessage.RecipientType.BCC);
    } catch (MessagingException e) {
        Debug.logError(e, module);
        return null;
    }
}
 
Example 10
Source File: MailEntityProcessor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void addEnvelopeToDocument(Part part, Map<String,Object> row)
    throws MessagingException {
  MimeMessage mail = (MimeMessage) part;
  Address[] adresses;
  if ((adresses = mail.getFrom()) != null && adresses.length > 0) row.put(
      FROM, adresses[0].toString());
  
  List<String> to = new ArrayList<>();
  if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) addAddressToList(
      adresses, to);
  if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) addAddressToList(
      adresses, to);
  if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) addAddressToList(
      adresses, to);
  if (to.size() > 0) row.put(TO_CC_BCC, to);
  
  row.put(MESSAGE_ID, mail.getMessageID());
  row.put(SUBJECT, mail.getSubject());
  
  Date d = mail.getSentDate();
  if (d != null) {
    row.put(SENT_DATE, d);
  }
  
  List<String> flags = new ArrayList<>();
  for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
    if (flag == Flags.Flag.ANSWERED) flags.add(FLAG_ANSWERED);
    else if (flag == Flags.Flag.DELETED) flags.add(FLAG_DELETED);
    else if (flag == Flags.Flag.DRAFT) flags.add(FLAG_DRAFT);
    else if (flag == Flags.Flag.FLAGGED) flags.add(FLAG_FLAGGED);
    else if (flag == Flags.Flag.RECENT) flags.add(FLAG_RECENT);
    else if (flag == Flags.Flag.SEEN) flags.add(FLAG_SEEN);
  }
  flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
  if (flags.size() == 0) flags.add(FLAG_NONE);
  row.put(FLAGS, flags);
  
  String[] hdrs = mail.getHeader("X-Mailer");
  if (hdrs != null) row.put(XMAILER, hdrs[0]);
}
 
Example 11
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 12
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testPrepareEmailForDisabledUsers() throws MessagingException
{
    String groupName = null;
    final String USER1 = "test_user1";
    final String USER2 = "test_user2";
    try
    {
        createUser(USER1, null);
        NodeRef userNode = createUser(USER2, null);
        groupName = AUTHORITY_SERVICE.createAuthority(AuthorityType.GROUP, "testgroup1");
        AUTHORITY_SERVICE.addAuthority(groupName, USER1);
        AUTHORITY_SERVICE.addAuthority(groupName, USER2);
        NODE_SERVICE.addAspect(userNode, ContentModel.ASPECT_PERSON_DISABLED, null);
        final Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, groupName);

        mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, "Testing");

        RetryingTransactionHelper txHelper = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);

        MimeMessage mm = txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>()
        {
            @Override
            public MimeMessage execute() throws Throwable
            {
                return ACTION_EXECUTER.prepareEmail(mailAction, null, null, null).getMimeMessage();
            }
        }, true);

        Address[] addresses = mm.getRecipients(Message.RecipientType.TO);
        Assert.assertEquals(1, addresses.length);
        Assert.assertEquals(USER1 + "@email.com", addresses[0].toString());
    }
    finally
    {
        if (groupName != null)
        {
            AUTHORITY_SERVICE.deleteAuthority(groupName, true);
        }
        PERSON_SERVICE.deletePerson(USER1);
        PERSON_SERVICE.deletePerson(USER2);
    }
}
 
Example 13
Source File: EmailerThread.java    From OpenRate with Apache License 2.0 4 votes vote down vote up
private String formatMailAddresses(MimeMessage msg)
{
  String addressList = null;
  int addressCount;

  try
  {
    // Get the To Mail addresses
    if (msg.getRecipients(RecipientType.TO) != null)
    {
      addressCount = msg.getRecipients(RecipientType.TO).length;
      for (int i = 0 ; i < addressCount ; i++)
      {
        if (i > 0)
        {
          addressList = addressList + "," + msg.getRecipients(RecipientType.TO)[i].toString();
        }
        else
        {
          addressList = "TO: " + msg.getRecipients(RecipientType.TO)[i].toString();
        }
      }
    }

    // Get the To CC addresses
    if (msg.getRecipients(RecipientType.CC) != null)
    {
      addressCount = msg.getRecipients(RecipientType.CC).length;
      for (int i = 0 ; i < addressCount ; i++)
      {
        if (i > 0)
        {
          addressList = addressList + "," + msg.getRecipients(RecipientType.CC)[i].toString();
        }
        else
        {
          addressList = addressList + " CC: " + msg.getRecipients(RecipientType.CC)[i].toString();
        }
      }
    }
  } catch (MessagingException ex)
  {
    addressList = "Unknown";
  }

  return addressList;
}
 
Example 14
Source File: MimeProperties.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private void initWithMimeMessage(MimeMessage mime) {
    try {
        if (mime.getSubject() != null) {
            subject = mime.getSubject();
        }

        if (mime.getFrom() != null) {
            from = mime.getFrom()[0].toString();
        }

        Address[] addresses;
        addresses = mime.getRecipients(Message.RecipientType.TO);
        if (addresses != null) {
            to = addresses[0].toString();
        }

        addresses = mime.getRecipients(Message.RecipientType.CC);
        if (addresses != null) {
            cc = addresses[0].toString();
        }

        addresses = mime.getRecipients(Message.RecipientType.BCC);
        if (addresses != null) {
            bcc = addresses[0].toString();
        }

        addresses = mime.getReplyTo();
        if (addresses != null) {
            replyTo = addresses[0].toString();
        }

        if (mime.getContent() instanceof String) {
            body = mime.getContent().toString().trim();
            log.info("ContentTypeString: " + mime.getContentType());
            log.info("ContentString: " + mime.getContent().toString().trim());
        }

        if (mime.getContent() instanceof Multipart) {
            Multipart multipart = (Multipart) mime.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String content = getContentAsString(bodyPart);
                log.info("ContentTypeMultiPart: " + bodyPart.getContentType());
                log.info("Content: " + content);
                multiPartsList.add(content);
            }
        }

    } catch (MessagingException | IOException me) {
        throw new IllegalStateException(me);
    }
}
 
Example 15
Source File: MailUtils.java    From keycloak with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param message email message
 * @return first recipient of the email message
 * @throws MessagingException
 */
public static String getRecipient(MimeMessage message) throws MessagingException {
    Address[] recipients = message.getRecipients(MimeMessage.RecipientType.TO);
    return recipients[0].toString();
}