Create, Send, Route an Email with a template an attachment

As the title suggests, I want to Create an email from a template and attach a file.  I also want the option to send the email or route to a queue for validation before manually hitting Send.

The purpose for the is an invoice process. Generate a batch of invoices, create a PDF from a PDF template , attach the file to a templated email etc…

Firstly, create an email from a template.  The template has been created and is saved as an Email Template:

  1. // Create an e-mail message using a template.
  2. InstantiateTemplateRequest instTemplateReq = new InstantiateTemplateRequest
  3. {
  4.     TemplateId = fetchTemplateId(LocalName),
  5.     ObjectId = Id,
  6.     ObjectType = "invoice"
  7. };
  8. InstantiateTemplateResponse instTemplateResp = null;
  9. Entity eMail = null;
  10.  
  11. try
  12. {
  13.     instTemplateResp = (InstantiateTemplateResponse)helper.Execute(instTemplateReq, true);
  14. }
  15. catch (Exception ex)
  16. {
  17.     log.Write(this, "Failed to create email from template (using " + LocalName + ") " + ex.Message.ToString());
  18. }

 

Using the InstantiateTemplateRequest, I need to specify the templateid (derived the the PDF template name),the objectid (the previously created invoiceid) and the objecttype – the invoice.

The result is an email Entity:

  1. eMail = instTemplateResp.EntityCollection.Entities[0];

 

From this point I can create my PDF and attach:

  1. // Fetch invoicenumber and add to parameters
  2. string prefix = "topmostSubform[0].Page1[0].";
  3. string invno = fetchInvoiceNumber(Id);
  4. Parameters.Add(new PDFParameter() { PathName = prefix + "invno[0]", Value = invno });
  5.  
  6. writeEmailAttachmentToCrm(emailId, "email", invno + ".pdf", createPDFArray(LocalName, Parameters));

 

Depending on the parameters passed I need to either SEND or ROUTE to an invoice queue for checking:

  1.  
  2. if (Send)
  3. {
  4.     // Send the email
  5.     SendEmailRequest send = new SendEmailRequest();
  6.     send.EmailId = emailId;
  7.     send.TrackingToken = "";
  8.     send.IssueSend = true;
  9.  
  10.     //SendEmailResponse sendEmailresp = (SendEmailResponse)helper.Execute(send, true);
  11. }
  12. else
  13. {
  14.     // write to queue
  15.     AddToQueueRequest routeRequest = new AddToQueueRequest
  16.     {
  17.         Target = new EntityReference("email", emailId),
  18.         DestinationQueueId = Guid.Parse("3CEB6F78-2698-E111-9B55-782BCB776B8C")
  19.     };
  20.  
  21.     helper.Execute(routeRequest, true);
  22.  
  23. }

 

During testing , I’ve taken precautions to NOT send emails:

1. Comment out the SendRequest

2. Hardcode the partyIds

3. Hardcode the Queue

Hopefully this demonstrates how easy it is to send templated emails with attachments. 

Oh Yes – the PDF routines – using iTextSharp:

  1. /// <summary>
  2. /// Create a PDFstream from a localfile
  3. /// </summary>
  4. /// <param name="LocalName"></param>
  5. /// <returns></returns>
  6. public PDFData CreatePDF(Guid Id, string LocalName, ObservableCollection<PDFParameter> Parameters)
  7. {
  8.     PDFData returnData = new PDFData();
  9.  
  10.     string currentDir = AppDomain.CurrentDomain.BaseDirectory + @"Templates\";
  11.  
  12.     PdfReader reader = new PdfReader(currentDir + LocalName );
  13.  
  14.     // filling in the form
  15.  
  16.     MemoryStream op = new MemoryStream();
  17.     PdfStamper stamp1 = new PdfStamper(reader, op);
  18.     AcroFields form1 = stamp1.AcroFields;
  19.  
  20.     foreach (PDFParameter parameter in Parameters)
  21.     {
  22.         try
  23.         {
  24.             form1.SetField(parameter.PathName, parameter.Value);
  25.         }
  26.         catch (Exception ex)
  27.         { }
  28.     }
  29.     stamp1.FormFlattening = true;
  30.     stamp1.Close();
  31.  
  32.     returnData.Data = op.ToArray();
  33.     returnData.Id = Id;
  34.  
  35.     op.Close();
  36.     op.Dispose();
  37.     reader.Close();
  38.  
  39.     return returnData;
  40. }

The PDF files are preformatted with placeholders (fields) to be substituted here .

This entry was posted in CRM 2011. Bookmark the permalink.

Comments are closed.