2011-04-04 87 views
1

我知道使用mailto链接可以打开您的defautl邮件客户端并填充主题和标题。我需要做类似的事情,但也要附上一份文件。.NET在Office 2010中创建带有附件的电子邮件

我的所有用户都将使用Outlook 2010,并将其设置为默认邮件客户端。它只需要为这种情况工作。

如何创建一个打开Outlook新消息窗口并填充附件字段的电子邮件?

回答

1

你需要到Outlook COM库的引用,那么这样的事情应该工作:

/// <summary> 
    /// Get Application Object 
    /// </summary> 
    public static OL.Application Application 
    { 
     get 
     { 
      try 
      { 
       return Marshal.GetActiveObject("Outlook.Application") as OL.Application; 
      } 
      catch (COMException) 
      { 
       return new OL.Application(); 
      } 
     } 
    } 

    /// <summary> 
    /// Prepare An Email In Outlook 
    /// </summary> 
    /// <param name="ToAddress"></param> 
    /// <param name="Subject"></param> 
    /// <param name="Body"></param> 
    /// <param name="Attachment"></param> 
    public static void CreateEmail(string ToAddress, string Subject, string Body, string AttachmentFileName) 
    { 
     //Create an instance of Outlook (or use existing instance if it already exists 
     var olApp = Application; 

     // Create a mail item 
     var olMail = olApp.CreateItem(OL.OlItemType.olMailItem) as OL.MailItem; 
     olMail.Subject = Subject; 
     olMail.To = ToAddress; 

     // Set Body 
     olMail.Body = Body; 

     // Add Attachment 
     string name = System.IO.Path.GetFileName(AttachmentFileName); 
     olMail.Attachments.Add(AttachmentFileName, OL.OlAttachmentType.olByValue, 1, name); 

     // Display Mail Window 
     olMail.Display(); 
    } 

对于这个工作,你还需要:

using System.Runtime.InteropServices; 
using OL = Microsoft.Office.Interop.Outlook; 
+0

难道我只是需要参考Office和Outlook Object库的? – Alice 2011-04-04 13:08:23

+0

我不断收到'对象'不包含'To'的定义,并且没有可以找到接受类型'object'的第一个参数的扩展方法'To'(你是否缺少using指令或程序集引用?认为参考是错误的。 – Alice 2011-04-04 13:15:56

+0

我使用VS2010与.Net 4,这使得olMail项目成为一个动态的对象,因此它的工作。我将更新代码,以便将olMail转换为适当的类型。 – JDunkerley 2011-04-05 15:40:42