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
sales4cesales4ce 

Email to apex Issue!

Hi,

 

I am using Email to apex to create a contact and task/event based on the subject of email.

Let me explain further. I first check for a contact using the email address and then if there are no records found i would then create the contact and a task to that contact.

Incase if i get a contact with same email address, i only need to create a task to that contact.

 

I have my email service setup and apex class compiling and saving without errors.

 

Now the Issue: The email would be sent in a specific format.

The format is :

 

First Name: Testing

Last Name : Email

E-Mail Address : test@email.com

 

From the above format my apex class should only pick the values on right side(values in red).

For this purpose i use substring method to get those values. Looks perfect until here.

 

The first thing of my Logic is to check if a contact already is there. so for this i use SOQL query,

[select Id from Contact where email=:c_email];, where c_email contains value "test@email.com"(from above).

 

Eventually for some reason i am not getting any rows returned even if there is a contact with same email address. I dont know whats happening here.

 

It does create a New contact with same email address.

 

I use a debug log to check if the email string is correct. My debug log shows correct email being filtered after using substring function.

 

One more important note, i tried to just send the email address without using substring function, the query works PERFECTLY.

But since my email would be of a specific format, i need that to pick it from there and check for existing contact.

 

I hope the problem is clear.

 

Can any one help me out here, if i am doing anything wrong?

 

Apex class:

global class ProcessApplicants implements
Messaging.InboundEmailHandler
{

    contact[] mycontact=new contact[0];
    
    global Messaging.InboundEmailResult handleInboundEmail
    (Messaging.InboundEmail email,Messaging.InboundEnvelope env)
    {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        string emailaddress=env.fromaddress;
        string e_Subject=email.Subject;
        string[] emailbody=email.plainTextBody.split('\n',0);
        string fname=emailbody[0].substring(12);
        string lname=emailbody[1].substring(11);
        string c_email=emailbody[2].substring(16);
        Datetime start_time=Datetime.Now();
        Datetime end_time=start_time.addhours(2);
        
        Contact inserted_Contact;
        contact existing_Contact;
                
        System.Debug('Email address after substring =='+c_email);
        try
        {
            //Contact[] existing_Contacts=[Select Id,email from Contact where email=:c_email limit 1];
            existing_Contact=[Select Id from Contact where email=:c_email limit 1];
            //existing_Contact=existing_Contacts[0];
            system.debug('Contact Id=='+existing_Contact.Id);
            if(e_Subject=='Registration Day')
            {
                Task[] myTask=new Task[0];
                myTask.add(new Task(Description='Testing Purpose',Subject='Make a Call',Priority='Normal',Status='Not Started',WhoId=existing_Contact.Id));
                insert myTask;
             }
             else
             {
                 Event[] myEvent=new Event[0];
                 myEvent.add(new Event(Subject='Junior Day',WhoId=existing_Contact.Id,EndDateTime=end_time,StartDateTime=start_time));
                 insert myEvent;
             }
        }
        
        catch(exception ex)
        {
            try
            {
              mycontact.add(new contact(FirstName=fname,LastName=lname,email=c_email));
              insert mycontact;
              inserted_Contact=mycontact[0];
          
              System.Debug('Contact Id_New=='+inserted_Contact.Id);
              if(e_Subject=='Registration Day')
              {
                  Task[] myTask= new Task[0];
                  myTask.add(new Task(Description='Testing Purpose',Subject='Make a Call',Priority='Normal',Status='Not Started',WhoId=inserted_Contact.Id));
                  insert myTask;
              }
              else
              {
                 Event[] myEvent=new Event[0];
                 myEvent.add(new Event(Subject='Junior Day',WhoId=inserted_Contact.Id,EndDateTime=end_time,StartDateTime=start_time));
                 insert myEvent;
              }
            }
        
            Catch(DMLException e)
            {
                System.Debug('Error in creating contact:'+e);
            }
         }
         
         
         
        
                                                                                                                                              
return result;
}
}

Debug Log:

18.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;VALIDATION,INFO;WORKFLOW,INFO
11:11:6.980|EXECUTION_STARTED
11:11:6.980|CODE_UNIT_STARTED|[EXTERNAL]ProcessApplicants.handleInboundEmail
11:11:6.981|METHOD_ENTRY|[13,28]|String.split(String, Integer)
11:11:6.981|METHOD_EXIT|[13,28]|split(String, Integer)
11:11:6.981|METHOD_ENTRY|[14,35]|String.substring(Integer)
11:11:6.981|METHOD_EXIT|[14,35]|substring(Integer)
11:11:6.981|METHOD_ENTRY|[15,35]|String.substring(Integer)
11:11:6.981|METHOD_EXIT|[15,35]|substring(Integer)
11:11:6.981|METHOD_ENTRY|[16,37]|String.substring(Integer)
11:11:6.981|METHOD_EXIT|[16,37]|substring(Integer)
11:11:6.981|METHOD_ENTRY|[17,29]|Datetime.Now()
11:11:6.981|METHOD_EXIT|[17,29]|now()
11:11:6.981|METHOD_ENTRY|[18,27]|Datetime.addhours(Integer)
11:11:6.981|METHOD_EXIT|[18,27]|addHours(Integer)
11:11:6.981|METHOD_ENTRY|[23,9]|System.Debug(String)
11:11:6.981|USER_DEBUG|[23,9]|DEBUG|Email address after substring == test@email.com
11:11:6.981|METHOD_EXIT|[23,9]|debug(ANY)
11:11:6.981|SOQL_EXECUTE_BEGIN|[27,30]|Aggregations:0|Select Id from Contact where email=:c_email limit 1
11:11:7.2|SOQL_EXECUTE_END|[27,30]|Rows:0|Duration:21
11:11:7.3|EXCEPTION_THROWN|[27,30]|System.QueryException: List has no rows for assignment to SObject
11:11:7.3|METHOD_ENTRY|[48,15]|LIST:SOBJECT:Contact.add(SOBJECT:Contact)
11:11:7.3|METHOD_EXIT|[48,15]|add(ANY)
11:11:7.3|DML_BEGIN|[49,15]|Op:Insert|Type:Contact|Rows:1
11:11:7.272|DML_END|[49,15]|
11:11:7.272|METHOD_ENTRY|[52,15]|System.Debug(String)
11:11:7.273|USER_DEBUG|[52,15]|DEBUG|Contact Id_New==003A0000009ICPEIA4
11:11:7.273|METHOD_EXIT|[52,15]|debug(ANY)
11:11:7.273|METHOD_ENTRY|[56,19]|LIST:SOBJECT:Task.add(SOBJECT:Task)
11:11:7.273|METHOD_EXIT|[56,19]|add(ANY)
11:11:7.273|DML_BEGIN|[57,19]|Op:Insert|Type:Task|Rows:1
11:11:7.471|DML_END|[57,19]|
11:11:7.476|CUMULATIVE_LIMIT_USAGE
11:11:7.476|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 1 out of 100
Number of query rows: 0 out of 10000
Number of SOSL queries: 0 out of 20
Number of DML statements: 2 out of 100
Number of DML rows: 2 out of 10000
Number of script statements: 22 out of 200000
Maximum heap size: 0 out of 12000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 10
Number of record type describes: 0 out of 10
Number of child relationships describes: 0 out of 10
Number of picklist describes: 0 out of 10
Number of future calls: 0 out of 10
Number of find similar calls: 0 out of 10
Number of System.runAs() invocations: 0 out of 20

11:11:7.476|CUMULATIVE_LIMIT_USAGE_END

11:11:7.476|CODE_UNIT_FINISHED
11:11:7.476|EXECUTION_FINISHED
imuinoimuino

I would check if there is any other character on the email that is not being showed, a blank space or something, debug the email length to se if it match with the length of visible character. Or simply try to trim the email so if there is some blank space it will remove it.

sales4cesales4ce

Hi,

 

Thanks, You were right there was a space. and hence query was unable to pick it up.

Crazy some times, a small space created the problem!

 

Also when i try to write a test class i am getting the following error.

 

Compile Error: Method does not exist or incorrect signature: [SOBJECT:Task].handleInboundEmail(Messaging.Inboun dEmail, Messaging.InboundEnvelope) at line 94 column 8

 

Can you please help me in writing the test case in this scenario.

 

Here is my Test Method:

 

Static testMethod void testTasks()
    {
        Messaging.InboundEmail email = new Messagi ng.InboundEmail();
        Messaging.InboundEnvelope env = new Messag ing.InboundEnvelope();

        email.plainTextBody='Test, Last, TLast@email.com, july 2010';
        email.fromaddress='Sales4ce@gmail.com ';
        email.Subject='Registration Day';
        string[] emailbody=email.plainTextBody.spl it(',',0);
        string fname=emailbody[0];
        string lname=emailbody[1];
        string c_email=emailbody[2];
        string grad_day=emailbody[3];
}