Let's see how PDF file is attached to an Email and sending programmatically. Lets see why this is important.
1) Email Templates cannot be created with an attachment. (Ironically!)
2) If we attach programmatically we can change the attachment based on logic if required.
In Summery, we can initiate Email in Draft state, then attach the PDF and then send.
Lets see the code
// Initiate Email in Draft state // Create Attachment byte[] embededPdf = LoadEmbeddedPdf("PluginProject.Resources.ApplicationForm.pdf") Guid attachmentId = CreatePdfAttchment(OrgSvc,emailId, Convert.ToBase64String(embededPdf)); // Send Email // Methods to use private byte[] LoadEmbeddedPdf(string resourceName) { var assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { if (stream == null) throw new FileNotFoundException("Embedded PDF file not found: " + resourceName); using (MemoryStream ms = new MemoryStream()) { stream.CopyTo(ms); return ms.ToArray(); } } } public Guid CreatePdfAttchment(IOrganizationService OrgSvc, Guid emailId, string base64Pdf) { Entity attachment = new Entity("activitymimeattachment"); attachment["subject"] = "Application Form"; attachment["filename"] = "ApplicationForm.pdf"; attachment["mimetype"] = "application/pdf"; attachment["body"] = base64Pdf; attachment["attachmentnumber"] = 1; attachment["objectid"] = new EntityReference("email", emailId); attachment["objecttypecode"] = "email"; return OrgSvc.Create(attachment); }
One important thing here is you need to pass correct path of the PDF is saved within the Project. LoadEmbeddedPdf() needs to be passed with correct path as below standered.
<Project Namespace><Folder><filename>.pdf
So you will realize when I pass PluginProject.Resources.ApplicationForm.pdf, my project namespace is PluginProject, folder name is Resources and pdf file name is ApplicationForm.pdf.
No comments:
Post a Comment