通过outlook C#预定义模板上的电子邮件

时间:2011-12-15 21:05:36

标签: c# asp.net email email-client

我需要根据路径保存的模板发送自动电子邮件:

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

1 个答案:

答案 0 :(得分:0)

//使用此作为示例我想知道网络路径是否有问题正在解决什么错误 //你还得到了吗? “〜/ Content / emailTemplate / emailTemplate.oft”你需要获得网络上的相对路径。用您的值和变量替换下面的示例。

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