+ Start a Discussion
CMcCaulCMcCaul 

Creating EmailMessage object from inbound email from email services

I am trying to implement my own email-to-case class and I have the following code, which is working in my sandbox, to create an EmailMessage on a case using email services:
 
EmailMessage[] newEmail = new EmailMessage[0];
 
newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
FromName = email.fromName,
ToAddress = email.toAddresses[0],
Subject = email.subject,
TextBody = email.plainTextBody,
HtmlBody = email.htmlBody,
ParentId = newCase[0].Id, 
ActivityId = newTask[0].Id));   // (newCase and newTask are the newly created case and task from earlier code)
 
insert newEmail;
 
I have several questions.  Is it possible to set the email message status to "New"?  If I attempt to add "Status = 'New'" in the .add() method I get an error: Message: Insert failed. First exception on row 0; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, Status: bad value for restricted picklist field: New: [Status] null.  If I don't attempt to set the status, it defaults to "Sent".
 
Also, does anyone have any sample code to share that adds headers and attachments from an inbound email to an Email Message object?  I'm struggling with that one.
 
Another minor issue that is bugging me is that in the Email Section of the Case page in my sandbox, the column labelled "Email Address" shows the 'to address' and my production version using the the standard SFDC email to case application will have the 'from address' (contact's address) displayed.  Does anyone know what field in the Email Message object this data comes from?
 
Thanks for the help!
Best Answer chosen by Admin (Salesforce Developers) 
GoForceGoGoForceGo
Okay, I figured it out...Too bad it's not documented. Spent a whole day trying to figure this stuff out.

You can pass a Status = '0'.

'0' = New
'1' = Read
'2' = Replied
'3' = Sent
'4' = Forwarded...

All Answers

fedeLfedeL
hi CMcCaul

I am trying to do the same thing. Did you succeed?
Your code works fine on a developer account, but same code does not work on a sandbox/enterprise account. Did your get it work on a production enviroment?

thanks a lot for your help.
GoForceGoGoForceGo
Okay, I figured it out...Too bad it's not documented. Spent a whole day trying to figure this stuff out.

You can pass a Status = '0'.

'0' = New
'1' = Read
'2' = Replied
'3' = Sent
'4' = Forwarded...

This was selected as the best answer
AiledrocAiledroc
Did you ever figure out how to add attachments to a new EmailMessage?  I'm attempting to do the same thing but can't find any documentation.
GoForceGoGoForceGo

Seems like there is a method called setFileAttachments.

 

You would create EmailFileAttachment objects and set their body to be the Blob of a salesforce attachment or document object you want to sent. 

 

 

 

 

CMcCaulCMcCaul

Here's my code. This is a little old and some of this may be replaced by newer functionality in apex.

 

// Add any binary attachments to the case
    if (email.binaryAttachments!=null && email.binaryAttachments.size() > 0) {
        for (i = 0 ; i < email.binaryAttachments.size() ; i++) {
            try {
                if (email.binaryAttachments[i].filename != null) {
                    Attachment newAttachment = new Attachment(ParentId = rwCase[0].Id,
                    Name = email.binaryAttachments[i].filename,
                    Body = email.binaryAttachments[i].body);
                    insert newAttachment;
                    System.debug('New Binary Attachment: ' + newAttachment );
                }
            }
            catch (Exception e) {
            System.debug('\n\nError:: ' + e + '\n\n');
            sendDebugEmail('Error adding binary attachment: ' + e.getMessage() + crlf + e.getCause() + crlf + crlf + 'To: ' + email.toaddresses[0] + crlf + 'From: ' + email.fromaddress + crlf + email.fromname + crlf + 'Subject: ' + email.subject + crlf + 'CaseId:' + caseThreadId, emailtype);
            }
        }
    }

// Add any text attachments to the case
    if (email.textAttachments!=null && email.textAttachments.size() > 0) {
        for (i = 0 ; i < email.textAttachments.size() ; i++) {
            try {
                if (email.textAttachments[i].filename != null) {
                    Attachment newAttachment = new Attachment(ParentId = rwCase[0].Id,
                    Name = email.textAttachments[i].filename,
                    Body = Blob.valueOf(email.textAttachments[i].body) );
                    insert newAttachment;
                    System.debug('New Text Attachment: ' + newAttachment );
                }
            }
            catch (Exception e) {
            System.debug('\n\nError:: ' + e + '\n\n');
            sendDebugEmail('Error adding text attachment: ' + e.getMessage() + crlf + e.getCause() + crlf + crlf + 'To: ' + email.toaddresses[0] + crlf + 'From: ' + email.fromaddress + crlf + email.fromname + crlf + 'Subject: ' + email.subject + crlf + 'CaseId:' + caseThreadId, emailtype);
            }
        }
    }

Glenn WeinsteinGlenn Weinstein

Just wanted to say THANKS for the excellent sample code in this thread, which worked perfectly in my efforts to write a custom email service to handle certain kinds of forwarded emails.  The code for creating an EmailMessage record (and setting its status!), and for passing the attachments through to the Case record, was fantastic.

 

One thing that tripped me up awhile - at first, my code seemed to think that none of my test emails had any attachments.  After scouring the code awhile, it occurred to me to check the Email Service settings in SFDC - and sure enough, I found an "Accept Attachments" field set to "None".  I flipped this to "All" and everything worked.

 

Thanks again for sharing!

colemabcolemab

What version of the API did you develop this on?  I ask because on v24 I get the error "Invalid type: EmailMessage" when trying to mock up your code.

 

Thanks

 

*** Edit: We don't have email to case turned on and it appears this object only applies to cases - so it isn't what I need.

CMcCaulCMcCaul

Wow, this was a long time ago.  I think the API version was 12 or 14.  But it's still working here!

dimetrius.bydimetrius.by

Hi,

 

You should enable email to case option and EmailMessage object will be accessible.

 

To enable it please go to:

Setup -> Customize -> Cases -> Email-to-Case.

 

Hope it helps

 

Thanks

Santosh SSantosh S

Using 'Mass Email Lead' option for sending Email to particular Lead

 

Need help to track the click on the link (inside the email) by the Email receiver (only the count of Click on the link to be tracked)

 

 

Please Help

 

Warm Regards

Kevin Chiles 930Kevin Chiles 930
@goforcego you nailed it!  This was killing my face for most of the morning.  Thanks!
TheDeckbladTheDeckblad
Thanks for the help on this. 
Ailedroc's question still stands. How the heck do you properly associate Attachments to EmailMessages when we cant use an external ID and no field on emailmessage is updateable?
HariPHariP
new status value
'5' - Draft
Kevin KneipKevin Kneip
I love you! I would hug you if I could. Just spent hours wondering why my trigger was not working. 
SBgooSBgoo
guys, we have a separate billing system that sends emails to customers.

I was trying to do the same as per this article in order to track those emails in SF thanks to BCC including a tracker and then managed by an email service. But then I realized that maybe emailmessage is not the right object to store "outbound" emails (i.e. sent by my organization as a whole, not strictly via SForce) as the status

'0' = New
'1' = Read
'2' = Replied
'3' = Sent
'4' = Forwarded...

seems to refer to something that will send emails. Or maybe the 'Sent' status would be the right one for this use case?

Thanks
 
sebastiano sassanosebastiano sassano
hi,
i have the same issue when i try to store the email, in the fields "Status" an "ActivityId"., but i'm using Json to do this. Can you help me in someway?
jitendra sharma 23jitendra sharma 23
Status is read only field for email message with pre defined value and so you are getting bad piclist and restricted error . 
you need to choose 1 value from available picklist like
 
The status of the email. Possible values are:
0 (New)
1 (Read)
2 (Replied)
3 (Sent)
4 (Forwarded)
5 (Draft)
 
Gabriel Kremer 9Gabriel Kremer 9

When does Salesforce create a task when an EmailMassage was created?
I have to create an EmailMessage for a case but the EmailMessage doesn't show up in the activity timeline.
Is there any dependancy between the status and my Email? Acutally I tried the creation with status = 0 and status = 3. 
It never creates automatically a task. Even though one is created when the supportaddress gets an Email. :/ A strange mystery.

Gianluca Massini RosatiGianluca Massini Rosati
hi, u solved? task are not created if Enhanced Email  is enabled ( if you disable that, the system create a task and not  an EmailMessage object) but i can't see in the activity no one