1

I have an Email Service that creates Leads from 3rd party vendors. We now want to accept a UTM parameter, but the vendor can’t concatenate. In my class, how can I turn this (which is in the body of the email):

Marketing Referrer Content: Facebook
Marketing Referrer Medium: Displaypro
Marketing Referrer Campaign: Q32022_display
Marketing Referrer Source: Google
Marketing Referrer Term: 50Visa

Into this:

?utm_medium=displaypro&utm_source=google&utm_campaign=Q32022_Display&utm_content=facebook&utm_term=50Visa

For Additional Context: Sample Email:

A new lead from Lead Gen tool!

Submitted Form Data
Email: testing2@test.com
First Name: Dev2
Last Name: TestLead
Phone: 310-555-5555
Zip Code: 91403
Marketing Referrer Content: Facebook
Marketing Referrer Medium: Displaypro
Marketing Referrer Campaign: Q32022_display
Marketing Referrer Source: Google
Marketing Referrer Term: 50Visa

Current Class

//Description: This class accepts a a structured email from a 3rd party vendor and attempts to create a new Lead

public class EmailServiceInboundLead implements Messaging.InboundEmailHandler{
    public Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,Messaging.InboundEnvelope env)
    {
        // Create an InboundEmailResult object for returning the result of the Apex Email Service
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        
        Lead newLead = new Lead();
        newLead.FirstName = emailSearch(email.plainTextBody, 'First Name:');
        newLead.LastName = emailSearch(email.plainTextBody, 'Last Name:');
        newLead.Email = emailSearch(email.plainTextBody,'Email:');
        newLead.PostalCode = emailSearch(email.plainTextBody, 'Postal Code:');
        newLead.Company = 'not provided';
        newLead.Phone = emailSearch(email.plainTextBody,'Phone:');
        newLead.Description = email.plainTextBody;
        
        //variable to hold any errors
        Set <String> apexErrors = new Set<String>();

        try{
            insert newLead;
        } catch(DmlException e){
            apexErrors.add(e.getMessage() + ' Email Body: ' + email.plainTextBody);
        }

        //Use values from the Email to create a new EmailMessage
        EmailMessage emailMessage = new EmailMessage();
        emailMessage.status = '3'; // email was sent
        emailMessage.subject = email.subject;
        emailMessage.htmlBody = email.htmlBody;
        emailMessage.TextBody = email.plainTextBody;
        String[] toIds = new String[] {newLead.id};
        emailMessage.toIds = toIds;
        
        try{
            insert emailMessage;
        }catch(DmlException e){
            apexErrors.add(e.getMessage() + ' Email Body: ' + email.plainTextBody);
        }

        // Associate the EmailMessage to the Lead
        EmailMessageRelation r = new EmailMessageRelation();
        r.emailMessageId = emailMessage.Id;
        r.relationId = newLead.id;
        r.relationType = 'FromAddress';
        try{
            insert r;
        }catch(DmlException e){
            apexErrors.add(e.getMessage() + ' Email Body: ' + email.plainTextBody);
        }

        //Run Lead assignment Rule
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.AssignmentRuleHeader.useDefaultRule = TRUE;
        try{
            Database.update(newLead,dmo);
        }catch(DmlException e){
            apexErrors.add(e.getMessage() + ' Email Body: ' + email.plainTextBody);
        }

        //if there were any errors, send to Admin
        if (!apexErrors.isEmpty()) {
            ZocdocEmailUtility.sendAdminEmail('EmailServiceInboundLead Error', String.join(new List < String > (apexErrors), '<br/>'), !Test.isRunningTest());
        }
        
        result.success = true;
        return result;
    }
    
    //Parse through the email body to find a value and return its value
    public static String emailSearch(String emailBody, String type){
        if(String.isEmpty(emailBody)) return null;
        
        String stringLine;
        String returnString;
        
        //Split the email body lines out by returns (\n)
        for(String msgBodyLine : emailBody.split('\n')) {
            
            //if the current line has the text passed into the method in it grab the entire line and assign it to the stringLine variable
            if(!String.isEmpty(msgBodyLine) && msgBodyLine.containsIgnoreCase(type)) {
                stringLine = msgBodyLine;
                system.debug('stringLine = ' + stringLine);
                break;
            } 
        }
        //If the stringLine variable is not null trim the string at the colon which will provide you with a value. 
        if(stringLine != null) {
            system.debug('stringLine search = ' + stringLine);
            returnString = stringLine.split(':')[1].trim(); 

        }
        //return the found STRING
        return returnString;   
    }
    
}
0

1 Answer 1

2

It seems to me that you already have code that parses the lines in the email body: the emailSearch() method.

This is already being used by earlier lines in the main code body. Examples:

newLead.FirstName = emailSearch(email.plainTextBody, 'First Name:');
newLead.LastName = emailSearch(email.plainTextBody, 'Last Name:');

I have not looked into the emailSearch() code in detail, so this is obviously untested, but I would try to add code somewhere that does something like:

String UTM = '?';
UTM += 'utm_medium=' + emailSearch(email.plainTextBody, 'Marketing Referrer Medium:');
UTM += '&utm_source=' + emailSearch(email.plainTextBody, 'Marketing Referrer Source:');
...

If that does not give you exactly what you need, you may have to tweak the emailSearch() code to handle these inputs.

Then do whatever you need to with the UTM string

This is assuming that all of those items in the email body always exist and always will have values. If you want to build it when/if they do not all have values, then you may want to remove the & that I hardcoded at the beginning of the second parameter (and assumed to be in the subsequent parameters), then add some code to check for values before adding a & and the next parameter.

2
  • Thanks, this is usable! Sep 5, 2022 at 20:31
  • This can probably be improved by using String.replaceAll(), since it appears that all of the target parameters start with "Marketing Referrer". E.g. email.plainTextBody.replaceAll('Marketing Referrer (.*): (.*)\n', 'utm_$1=$2&'). Not perfect, but it should get you most of the way there.
    – Derek F
    Sep 5, 2022 at 20:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .