I am using an email service to update opportunities in my salesforce instance, what my handler does it lift any email addresses in the CC field and then does a search for the contact via SOQL, once found it will update a field with their ID in my Opportunities object, if not found it will create the contact and then add them to the Opp.

The problem I am having is that the person that is sending the emails also wants to cc himself so he has a copy of the email, how I can I strip out his email address from the array? Also is there a way that it will only read the first CC incase there are ever more than one address.


 // Find Designer(s) (from cc address)
        if(email.ccAddresses != NULL) {
          String contactName = '';
          String contactEmail = '';

          for (String address : email.ccAddresses) {
            Contact contact = new Contact();
            Matcher contactMatcher = Pattern.compile('<.+>').matcher(address);

            // Parse addresses to names and emails
            if (contactMatcher.find()) {
              String[] nameParts = address.split('[ ]*<.+>')[0].replace('"', '').split('[ ]+');

              contact.FirstName = nameParts.size() > 1 ? nameParts[0] : '';
              contact.LastName = nameParts.size() > 1 ? nameParts[nameParts.size()-1] : nameParts[0];
              contact.Email = contactMatcher.group().replaceAll('[<>]', '');
            } else {
              contact.LastName = address;
              contact.Email = address;

            // Add if new
            if ([select count() from Contact where Email = :contact.Email] == 0) {
              contact.AccountId = '001c000000cGKr7'; // set as default client
              insert contact;
              Opp.Designer__c = contact.id;
            } else {
              Contact con = [SELECT Id FROM Contact WHERE Email = :contact.Email];
              Opp.Designer__c = con.Id;

            contactName = contact.LastName;
            contactEmail = contact.Email;

        } // end if contacts cc'd

For the cc addresses you could do a pattern search to look for more than one xxxxx@.xxx email address using regEx following having done your name split operation and replaceAll('[<>]', '') where you remove any [, <, > or ] as I see you appear to be doing. You could also do a split operation wherever there's a comma as typically any additional addresses will have a comma separation between them.

There's also a compString method you can use to find any duplicates in case the original sender has cc'd themselves.

Needless to say, there are numerous ways to approach this depending on what you're most comfortable with.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.