[SalesForce] REQUIRED_FIELD_MISSING, No body specified in the file attachment:

I have a requirement whenever I create a record and upload a word file document in notes and attachment a trigger gets fired which send that attachment to a desired email address.

I have written this trigger which sends email when a record is created but when I try to add attachment code it shows this error.
REQUIRED_FIELD_MISSING, No body specified in the file attachment:
But when I check in debug I get the Body as Blob[0].

trigger SendMail on Random__c (after update) 
{

Set<ID> RandomIDs = new Set<ID>();
for(Random__c c : trigger.new)
{
    RandomIDs.add(c.id);

}
  List<Attachment> lstAttach = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId IN : RandomIDs];
 for(Candidate__c c : trigger.new)
{

   Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

    for(Attachment att : lstAttach)
    {
         // Create the email attachment

         Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();       
         efa.setFileName(att.Name);
         efa.Body = att.body;
         efa.setContentType('application/msWord');
         efa.setInline(false);
     email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

    }



    String subject = 'Sample subject ';
    email.setSubject(subject);

    String body = ' Sample Body '; 
    email.setPlainTextBody(body);

    email.setToAddresses(new String[]{'test@test.com'});

    if(email != null)
      {

        Messaging.sendEmail(new Messaging.singleEmailMessage[] {email});

      }
  }
}

Best Answer

There could be any of below reason .

  1. It seems to me that you are not using the correct method to attach a file as email attachment. There is no body method for EmailFileAttachment object

attach.Body = fileBody; --> should really be --> attach.setBody = fileBody;

  1. Avoid hardcoding contentType. Directly use attach.contentType

  2. When you say you get value in body. Ensure that you are checking the attachment body and not the email body.

  3. Also you used Candidate__c and Random__c for looping through trigger.new. Hope both are one and the same.

I tried out the exact code that you used and it works great for me without any error.

Related Topic