Salesforce: 将发送出去的带有附件的Email存储到相关数据的Activity History中
在需求中,客户希望可以将从salesforce中发送出去的email存储备份在相关数据下的Activity History中。
Salesforce提供了方法可以实现这一需求: mail.setSaveAsActivity(true)
setSaveAsActivity()是一个可选方法,它的默认值是true。但仅当mail设置了targetObjectId或targetObjectIds或whatId时它才会生效。
若设置了targetObjectId, 邮件会以Outbound Email Message的形式存储在相关的Contact的Activity History中;
若设置了whatId,邮件则存储在相关的sObject record的Activity History中。
若两个都设置了,它们的Activity History中都会显示这个Outbound Email Message。
参考代码:
Messaging.SingleEmailMessage[] emails = new Messaging.SingleEmailMessage[] {};
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00XC000000erT1MAI');
mail.setTargetObjectId('003C00000RFWJZ');
mail.setWhatId('a02n000000aJq0');
mail.setSaveAsActivity(true);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
值得注意一点的是:如果设置了TemplateId,则不要再设置Subject和Body,否则template将失效。
而如果发送出去的邮件带有附件,如:
Messaging.SingleEmailMessage[] emails = new Messaging.SingleEmailMessage[] {};
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00XC000000erT1MAI');
mail.setTargetObjectId('003C00000RFWJZ');
mail.setWhatId('a02n000000aJq0');
mail.setSaveAsActivity(true);
PageReference invoicePage = new PageReference('/apex/InvoicePDF');
invoicePage.getParameters().put('id', invoiceId);
invoicePage.setRedirect(false);
Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
fileAttachment.setBody(!Test.isRunningTest() ? invoicePage.getContentAsPDF() : Blob.valueOf('This is a test.'));
fileAttachment.setContentType('application/pdf');
fileAttachment.setFileName('test');
mail.setFileAttachments(new Messaging.EmailFileAttachment[]{ fileAttachment });
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
这种情况下Outboud Email Message只能保存邮件的内容,而无法保存附件。
这时我们就需要借助Email Service实现这一功能需求。
首先我们要在salesforce中创建一个email service,并为这个email service创建一个Apex Class以实现具体的功能。
GeneratePDFFromInboundEmail参考代码:
最后要将在Email Service中生成的Email Address添加到发送邮件的代码中,即可实现全部功能:
Messaging.SingleEmailMessage[] emails = new Messaging.SingleEmailMessage[] {};
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00XC000000erT1MAI');
mail.setTargetObjectId('003C00000RFWJZ');
mail.setWhatId('a02n000000aJq0');
mail.setBccAddresses(new List<String> { 'generate_invoice_pdf@apex.sandbox.salesforce.com' });
mail.setSaveAsActivity(true);
PageReference invoicePage = new PageReference('/apex/InvoicePDF');
invoicePage.getParameters().put('id', invoiceId);
invoicePage.setRedirect(false);
Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
fileAttachment.setBody(!Test.isRunningTest() ? invoicePage.getContentAsPDF() : Blob.valueOf('This is a test.'));
fileAttachment.setContentType('application/pdf');
fileAttachment.setFileName('test');
mail.setFileAttachments(new Messaging.EmailFileAttachment[]{ fileAttachment });
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });