.NET在Office 2010中创建带附件的电子邮件

时间:2011-04-04 11:54:55

标签: .net email c#-4.0 outlook outlook-2010

我知道通过mailto链接,您可以打开您的defautl邮件客户端并填充主题和标题。我需要做类似的事情,但也附上一份文件。

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

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

1 个答案:

答案 0 :(得分: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;