Search code examples
c#asp.netemailemail-client

Email on predefined template via outlook C#


I have a requirement to send automated emails based on a template saved at path :

HostingEnvironment.MapPath("~/Content/emailTemplate/emailTemplate.oft")

I am using code below to accomplishis this, it works fine without template by using (oApp.CreateItem()), but when i use oApp.CreateItemFromTemplate() instead of oApp.CreateItem() i get exception.

public static void CreateMessageWithAttachment(
          string invoiceNumber, string recipient,  string messageBody)
{

    Outlook.Application oApp = new Outlook.Application();
    Outlook.Folders folder = oApp.Session.GetDefaultFolder(
                               Outlook.OlDefaultFolders.olFolderDrafts) 
                                as Outlook.Folders;
    Outlook.MailItem email = oApp.CreateItemFromTemplate(
                               HostingEnvironment.MapPath(
                                "~/Content/emailTemplate/emailTemplate.oft"), folder)
                                   as Outlook.MailItem;

    email.Recipients.Add(recipient);
    email.Subject = "Invoice # " + invoiceNumber;

    {
      string fileName = invoiceNumber.Trim();
      string filePath = HostingEnvironment.MapPath("~/Content/reports/");
      filePath = filePath + fileName + ".pdf";
      fileName += ".pdf";
      int iPosition = (int)email.Body.Length + 1;
      int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
      Outlook.Attachment oAttach = email.Attachments.Add(
                           filePath, iAttachType, iPosition, fileName);
    }

    email.Display();
    ////..uncomment below line to SendAutomatedEmail emails atomaticallly
    ////((Outlook.MailItem)email).Send(); 
}

Solution

  • //use this as a example I wonder if the network path has issues being resolved what error //are you getting as well "~/Content/emailTemplate/emailTemplate.oft" you need to get the relative path on the network too. replace the sample below with your values and variables.

    private void CreateItemFromTemplate()
    {
        Outlook.Folder folder =
            Application.Session.GetDefaultFolder(
            Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
        Outlook.MailItem mail =
            Application.CreateItemFromTemplate(
            @""~/Content/emailTemplate/emailTemplate.oft", folder) as Outlook.MailItem;
        mail.Subject = "Congratulations";
        mail.Save();
    }