Wednesday, November 26, 2014

Trigger to send a PDF along with email in Salesforce

Trigger to send a PDF along with email in Salesforce


Trigger:


trigger sendEmail on Employee__c (after insert, after update)
{             
                List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                for(Employee__c e : trigger.new)
                { 
                Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                attach.setContentType('application/pdf');
                attach.setFileName('Employee.pdf');
               
                String body;
               
        body = '<html><h1 style=\"text-align:center;\">Employee Information</h1><br/><br/><table align=\"center\"><tr><td>Employee Name</td><td>' + e.Name + '</td></tr><tr><td>Age</td><td>' + e.Age__c + '</td></tr><tr><td>State</td><td>' + e.State__c + '</td></tr><tr><td>City</td><td>' + e.City__c + '</td></tr></table></html>';
                System.debug('HTML is ' + body);
               
                attach.Body = Blob.toPDF(body);
               
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(new String[] { e.Email__c });
                mail.setSubject('PDF Generation');
                mail.setHtmlBody('PFA');
                mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });        
               
                mails.add(mail);
                }
                if(!mails.isEmpty())
                {
                Messaging.SendEmail(mails);
                }

}


Generated PDF:









4 comments:

Arun said...

When i tried this code an error is occured during inserting a record.

System.InvalidParameterValueException: An error occurred while parsing the input string.: Trigger.TriggerSendEmail: line 18, column 1


line no. 18 is ---

attach.Body = Blob.toPDF(body);

please tell me how to do this .
thanks

Yakin said...

https://sourcecalendar.com/april-2018-calendar


https://sourcecalendar.com/july-2018-calendar


https://sourcecalendar.com/june-2018-calendar


https://sourcecalendar.com/may-2018-calendar

Yakin said...

https://sourcecalendar.com/april-2018-calendar


https://sourcecalendar.com/july-2018-calendar


https://sourcecalendar.com/june-2018-calendar


https://sourcecalendar.com/may-2018-calendar

Vishal said...

Ho to add image in email attachment?

Post a Comment

 
| ,