前篇文章介绍使用salesforce的trigger发email,但是我们发现他有很多的限制,
比如说,getContent()和getContentAsPDF()不能在Tigger和Batch里面调用
比如说,在PDF里面如果想加上图片,并且用Trigger把email的文章和图片都同时发出去的话,就有了以下的方法:
<apex:page renderAs="PDF">
<!-- Begin Default Content REMOVE THIS -->
<h1>Congratulations</h1>
This is your new Page
<!-- End Default Content REMOVE THIS -->
</apex:page>
Creating APEX based REST API with POST Method :
/**
* Created By : YuTao
* Description : Apex based REST API which exposes POST method to send Email
*/
@RestResource(urlMapping='/sendPDFEmail/*')
Global class GETPDFContent{
@HttpPost
global static void sendEmail(String EmailIdCSV, String Subject, String body) {
List<String> EmailIds = EmailIdCSV.split(',');
PageReference ref = Page.PDF_DEMO;
Blob b = ref.getContentAsPDF();
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
efa1.setFileName('attachment_WORK.pdf');
efa1.setBody(b);
String addresses;
email.setSubject( Subject +String.valueOf(DateTime.now()));
email.setToAddresses( EmailIds );
email.setPlainTextBody(Body);
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
REST API created using Apex class can be accessed from URL “https://<YOUR_SALESFORCE_INSTANCE>/services/apexrest/<RESTURL>”
继续创建新类:
/**
* Created By : Yu Tao
* Description : This class exposes @future method to send VF page rendered as PDF as attachment in Email
*/
public class SendVFAsAttachment{
@future(callout=true)
public static void sendVF(String EmailIdCSV, String Subject,String body,String userSessionId)
{
//Replace below URL with your Salesforce instance host
String addr = 'https://shivasoft--shiva1.cs6.my.salesforce.com/services/apexrest/sendPDFEmail';
HttpRequest req = new HttpRequest();
req.setEndpoint( addr );
req.setMethod('POST');
req.setHeader('Authorization', 'OAuth ' + userSessionId);
req.setHeader('Content-Type','application/json');
Map<String,String> postBody = new Map<String,String>();
postBody.put('EmailIdCSV',EmailIdCSV);
postBody.put('Subject',Subject);
postBody.put('body',body);
String reqBody = JSON.serialize(postBody);
req.setBody(reqBody);
Http http = new Http();
HttpResponse response = http.send(req);
}
}
Writing Trigger:
/**
* Created By : Yu Tao
* Description : This Trigger calls @future method to send VF page rendered as PDF as attachment in Email
* Note : Make sure that this Trigger does not call Future methods more than 10 times.
*/
trigger SampleTrigger on Lead (before insert) {
SendVFAsAttachment.sendVF('emailaddress1@email.com,emailaddress2@email.com','Sample Test from Trigger',
'Sample Email Body',UserInfo.getSessionId());
}