How to Put a Word Document on the Body of an Email in C#
- 1). Open Microsoft Visual C# Express and select "New Project..." on the left pane of your screen. Double-click "Console Application."
- 2). Click the "Project" menu, select "References" then click the "COM" tab. Select "Microsoft Word <version number> Object Library" and "Microsoft Outlook <version number> Object Library." Click "OK."
- 3). Press "Ctrl," "A" and "Delete" to remove existing code. Copy and paste the following code to your "Program.cs" module.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String WordText = "";
Application wrdApplication = new Application();
object missing = System.Reflection.Missing.Value;
Document wordDoc = wrdApplication.Documents.Open(@"G:\WordDoc.doc", ReadOnly: false, Visible: false);
wordDoc.Activate();
wordDoc.ActiveWindow.Selection.WholeStory();
WordText = wordDoc.ActiveWindow.Selection.Text;
Microsoft.Office.Interop.Outlook._Application olkApplication = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook._MailItem olkMailItem = (Microsoft.Office.Interop.Outlook._MailItem)
olkApplication.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
olkMailItem.Display(false );
olkMailItem.To = "joe.smith4534@aol.com";
olkMailItem.Subject = "Adding a word document";
olkMailItem.Body = WordText;
olkMailItem.Display(true);
olkMailItem.Send();
wordDoc.Close(false, missing, missing);
}
}
} - 4). Edit the following line of code and type the path for your Word document.
Document wordDoc = wrdApplication.Documents.Open(@"C:\WordDoc.doc", ReadOnly: false, Visible: false);
Press "F5" to run your program.