loading... Salesforce Cat

Thursday, December 4, 2014

Salesforce Sending Mail Attachments

Sending attachments via mail has become a common occurrence in everyday life.So it is not much of a surprise if you get a requirement to send and attachment via system generated mail as I did. So in this article I am going to discuss how to send an Word document generated by Visualforce as a mail attachment.I am going to use the Visualforce  Word document generated  in my previous post Render Visualforce Page As A Word Document  as the attachment for the purpose of this article.

given below is the Apex code for sending Word Form as an mail attachment.



     List<Messaging.SingleEmailMessage> EmailMessages= new List<Messaging.SingleEmailMessage>();  
     List<User> loggedUser = [Select Id,Name,Email from User where Id=:UserInfo.getUserId()];  
      Messaging.SingleEmailMessage EmailMsg = new Messaging.SingleEmailMessage();  
      //define mail body content -begin (here i used html tags to format my mail body because I am setting htmbody  
      String EmailBody = '<html><body> Dear User,<br/><br/>';  
      EmailBody ='Please Fill the attached document and send us';  
      EmailBody += '<br/><br/>Thank you,<br/>'+loggedUser[0].Name+'<br/><br/>';  
      EmailBody += '</body></html>';  
      //define mail body content -end  
      EmailMsg.setHtmlBody(EmailBody); // set the html body contnet  
      EmailMsg.setToAddresses(new String[]{'mailaddreses seperated by commas'});//set recipient mail addresses  
      EmailMsg.setSubject('SalesforceCat Demo');  
      EmailMsg.setReplyTo(loggedUser[0].Email);// set reply to email address becuase I expect this mailed to be replied  
      EmailMsg.setUseSignature(true);  
      PageReference Word = new PageReference('/apex/WordDownloadExample'); // url of ur visualforce page rendered as a word  
      //Word.getParameters().put('Id','xxxx'); if any parameters need to be passed to the page 
      Word.setRedirect(true); //do a virtual redirect to the page so we can get page content using page reference
      Blob b;  
      b = Word.getContent();// get the content of the page and assignment to blob  
     
      
      Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();// create an attachment instance  
      attachment.setBody(b); // set the blob as attachment content  
      attachment.setFileName('attach.doc'); // set the attachment name  
      EmailMsg.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment}); // link the attachment to the mail  
      EmailMessages.add(EmailMsg);  
      if(!Test.isRunningTest())  
      {  
      Messaging.sendEmail(EmailMessages);   
      }   

 Mail with word form as an attachment


Mail with Word attachment
mail sent


No comments:

Post a Comment