Wednesday 22 October 2014

Create Dynamically File And Attach In Mail Using Apex (Salesforce)



Here I am going to share code to create a run time document in apex code. and then attaching this document (txt file) in mail address.

Below in the code first creating a document then creating a instance of Messaging.EmailFileAttachment class then creating instance of Messaging.SingleEmailMessage class. EmailFileAttachment is used to add attachment in mail.


Document d = new Document();
     d.Name = 'ImportBatchResult';
     String myContent = 'this is a simple data. just testing use only. Right now we are testing the attechment file';
     d.Body = Blob.valueOf(myContent);
     d.ContentType = 'text/plain';
     d.Type = 'txt';
   
     Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
     efa.setFileName('BatchResultLog.txt');
     efa.setBody(d.Body );
   
     String[] toAddresses = new String[] {a.CreatedBy.Email};
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     mail.setToAddresses(toAddresses);
     mail.setFileAttachments(new Messaging.EmailFileAttachment[]{efa} );
 
     mail.setSubject('BatchImport Status: ' + a.Status);
     mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
      ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);
       
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

No comments:

Post a Comment