.NET creating an email with attachments in Office 2010
I know with an mailto 开发者_如何转开发link you can open your defautl mail client and populate a subject and a title. I need to do something similar but also attach a document.
All my users will be using Outlook 2010 and it will be set as there default mail client. It only needs to work for that case.
How can you create an email that opens up the Outlook new message window and populates the attachment field?
You'll need a reference to the Outlook COM library, then something like this should work:
/// <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();
}
For this to work you would also need:
using System.Runtime.InteropServices;
using OL = Microsoft.Office.Interop.Outlook;
精彩评论