function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Peter Martensen 8Peter Martensen 8 

Why is this outbound email being logged as a Task? I'm using an Apex inbound email handler.

I'm using the included Apex Class to capture inbound emails using an Email Service.  When I send an email from a record, that email is immediately duplicated as a Task also.  How do I prevent that from happening?  When I send an email without using the Email Service email address in the CC field, this doesn't happen.
Thanks!
User-added image
global with sharing class attachEmail implements Messaging.InboundEmailHandler {
    //handler overwrite
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
                                                        Messaging.InboundEnvelope env) {
    //local variables
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    String myPlainText= '';
    myPlainText = email.plainTextBody;
    Integer i = myPlainText.indexOf('ref:',0);                                                   
    String objectId = myPlainText.substring(i+5, i+20);
Task[] newTask = new Task[0];       
                                                            
    //try to do something here
    try {
      newTask.add(new Task(Description =  myPlainText,
           TaskSubtype = 'Email',
           Priority = 'Normal',
           Status = 'Inbound Email',
           Subject = email.subject,
           IsReminderSet = true,
           ReminderDateTime = System.now()+1,
           WhatId = objectId));
      insert newTask;       
    }
    catch (Exception e) {
        System.debug('Email failed ' + e);
    }
    result.success = true;

    return result;
    }
}

 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Peter,

When we look at the code we see that the emails are getting added to tasks list and then at the end, you are inserting the whole task list this might be the reason as you are creating tasks the emails are being attached as tasks.

In case if the above helped in addressing your issue can you please choose this as best answer so that it can be used by others in the future.

Regards,
Anutej
Peter Martensen 8Peter Martensen 8
Anutej,
I was wrong, deleting "insert newTask;" prevented the inbound emails from being logged.  Can you tell me how to modify that code so that the inbound email is stored as an email and not a Task?
Thanks,
Peter
ANUTEJANUTEJ (Salesforce Developers) 
Hi Peter,

I found your implementation in the documentation that states "
inbound email address and create a new task".

>> https://help.salesforce.com/articleView?id=code_inbound_email.htm&type=5

However, I found a feed thread that has a somewhat similar requirement can you please have a look at it once and in case if it helps can you please choose this as best answer so that it can be used by others in the future.

>> https://success.salesforce.com/answers?id=9063A000000DY8FQAW

Regards,
Anutej
Peter Martensen 8Peter Martensen 8
I changed the Apex Class to create an email instead.  I created a Lookup field on the Emailmessage Object and saved the recordId to that field so that the email message would show up in a Related List on the Opportunity.
global with sharing class attachEmailToOpportunity implements Messaging.InboundEmailHandler {
    //handler overwrite
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
                                                        Messaging.InboundEnvelope env) {
    //local variables
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    String myPlainText= '';
    myPlainText = email.plainTextBody;
    Integer i = myPlainText.indexOf('ref:',0);                                                   
    String objectId = myPlainText.substring(i+5, i+20);
    System.debug('recordId '+objectId);
         try {
            EmailMessage            createEmail = new EmailMessage(
                Subject                        = email.Subject
                ,Status                         = '2'
                ,FromAddress                    = email.fromAddress
                ,FromName                       = email.fromName
                ,Headers                        = JSON.serialize( email.headers )
                ,HtmlBody                       = email.htmlBody
                ,TextBody                       = email.plainTextBody
                ,Incoming                       = true
                ,MessageDate                    = DateTime.now()
                ,RelatedToId                    = objectId
                ,Opportunity__c                 = objectId
            );
            insert createEmail;
            System.debug('Created Email');
            new Object[]{email};
    }
    catch (Exception e) {
        System.debug('Email failed ' + e);
    }
    result.success = true;

    return result;
    }
}

 
ANUTEJANUTEJ (Salesforce Developers) 
Hmm, so were you able to send mail to multiple recipients in the cc field??
Peter Martensen 8Peter Martensen 8
I didn't try to add multiple email addresses to the CC field.  But it would be easy to do as long as you had a ";" between them.