I have written some apex code to create a case when an email is sent to the support email. It's working great but sometimes when a customer sends an email with attachments the attachments get inserted but not the email message. Below is my code for inserting the email.

    public static EmailMessage InsertEmailMessage(Messaging.inboundEmail email, Case c){
    System.debug('Inserting Email');
    em = new EmailMessage();
    string toaddress = string.join(email.toAddresses,',');
    em.ToAddress = toaddress;
    em.Subject = email.subject;
    em.TextBody = email.plainTextBody;
    em.FromAddress = email.replyTo;
    em.HtmlBody = email.htmlBody;
    em.ParentId = c.Id;
    em.Incoming = true;
    em.FromName = email.fromName;

    // Save attachments, if any
    List<Attachment> attachments = new List<Attachment>();
    if(email.textAttachments != null)
        for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
            Attachment attachment = new Attachment();
            attachment.Name = tAttachment.fileName;
            attachment.Body = Blob.valueOf(tAttachment.body);
            attachment.ParentId = c.Id;
    if(email.binaryAttachments != null)
        for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
            Attachment attachment = new Attachment();
            attachment.Name = bAttachment.fileName;
            attachment.Body = bAttachment.body;
            attachment.ParentId = c.Id;
    if(attachments.size() > 0)
        insert attachments;
    insert em;
    return em;

What would cause EmailMessage to be randomly not inserting the email message? I was unable to reproduce the issue but we have received more than one complain.

  • By saying I was unable to reproduce the issue, do you mean you have been able to identify emails (pointed out by end user) that has this issue and using the same email doesn't cause this problem? – arut Oct 2 '20 at 5:17
  • @arut - I thought that this was related to the user having send the email from outlook so I tried to send an email using outlook and everything worked fine. – Laura Bejjani Oct 2 '20 at 12:17
  • You should incorporate some exception handling in the code (in case this issue reoccurs). – arut Oct 2 '20 at 17:18
  • The issue is still there for the customer I just haven't been able to reproduce it myself – Laura Bejjani Oct 2 '20 at 17:20
  • So did you get the email from the user & use it? or, just try an email from your end? Is this user having problem on all the emails he/she sends (could be a permission issue?)? – arut Oct 2 '20 at 18:45

Your Answer

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

Browse other questions tagged or ask your own question.