通过outlook c#在预定义模板上发送电子邮件

本文关键字:电子邮件 outlook 预定义 通过 | 更新日期: 2023-09-27 18:17:55

我需要根据保存在path:

的模板自动发送电子邮件。

HostingEnvironment.MapPath(~/内容/emailTemplate/emailTemplate.oft)

我使用下面的代码来完成这一点,它工作得很好没有模板使用(oApp.CreateItem()),但当我使用oApp.CreateItemFromTemplate()代替oApp.CreateItem()我得到异常。

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(); 
}

通过outlook c#在预定义模板上发送电子邮件

//以此为例,我想知道网络路径是否有问题正在解决什么错误//你得到了什么"~/内容/emailTemplate/emailTemplate。通常,您还需要获得网络上的相对路径。将下面的示例替换为您的值和变量。

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();
}