Solved

How can I automate Outlook and Word by using Visual C# .NET to create a e-mail message?

Posted on 2008-11-03
4
1,078 Views
Last Modified: 2013-11-27
As the title may indicate, I'm trying to get one of my applications to be able to send an email.  I found an article from Microsoft that seemed to solve the problem:

http://support.microsoft.com/default.aspx?id=819398

The problem is that this article is targeted at Word 2002/2003, and I have word 2007.  I assumed that this wouldn't be a big deal, and that the same code should work for Word 2007.  It appears I was wrong.  When I attempted to use the code described I got a COMException was unhandled error ("Command Failed") on the line:

Document doc = wApp.Documents.Add(
                        ref template,
                        ref newTemplate,
                        ref documentType,
                        ref visible);

How can I fix this error, or more generally, how can I send an email from a Visual Studio project (using Outlook)?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;
using Microsoft.Office.Interop.Word;
using System.IO;
 
namespace EmailTestApp
{
	public class MyApi
	{
 
		[DllImport("user32.dll")]
		public static extern int FindWindow(string strclassName, string strWindowName);
	};
	
 
 
	public partial class Form1 : Form
	{
 
		
 
		private Microsoft.Office.Interop.Word.Application wApp;
		public Form1()
		{
			InitializeComponent();
		}
 
		private void button1_Click(object sender, System.EventArgs e) { CreateEmailMessage(); }
 
		private void CreateEmailMessage()
		{
			//Initialize the envelope values.
			string strTo = "yourname@yourdomain.com";
			string strBCC = "yourname@yourdomain.com";
			string strCC = "yourname@yourdomain.com";
			string strSubject = "Outlook Automation";
			string strBody = "HTMLPage1.htm";
 
			//Automate the Word document.
			wApp = new Microsoft.Office.Interop.Word.Application();
			wApp.Visible = false;
			object template = System.Reflection.Missing.Value;
			object newTemplate = System.Reflection.Missing.Value;
			object documentType = WdNewDocumentType.wdNewEmailMessage;
			object visible = false;
			wApp.Visible = false;
			Document doc = wApp.Documents.Add(
				ref template,
				ref newTemplate,
				ref documentType,
				ref visible);
 
			//Automate the Outlook mail item.
			MailItemClass mItem = (MailItemClass)doc.MailEnvelope.Item;
			mItem.To = strTo;
			mItem.BCC = strBCC;
			mItem.CC = strCC;
			mItem.Subject = strSubject;
			mItem.BodyFormat = OlBodyFormat.olFormatHTML;
			mItem.HTMLBody = GetString(strBody);
			mItem.ItemEvents_Event_Close += new ItemEvents_CloseEventHandler(this.wApp_Close);
 
			wApp.Visible = true;
 
			// Loop until there are no more references to release.
			while (Marshal.ReleaseComObject(mItem) > 0) ;
			mItem = null;
 
			// Invoke the .NET garbage collector.
			GC.Collect();
			GC.WaitForPendingFinalizers();
		}
		// Close the Word application after the message has been sent.
		private void wApp_Close(ref bool e)
		{
			object oMissing = System.Reflection.Missing.Value;
			wApp.Quit(ref oMissing, ref oMissing, ref oMissing);
		}
 
		// Get the body of the e-mail.
		private string GetString(string filename)
		{
			string strFileStreamText = "";
			string strTempRead = "";
			try
			{
				if ("" == filename)
				{
					filename = "HTMLPage1.htm";
				}
				System.IO.Stream fin = File.OpenRead(filename);
				System.IO.StreamReader sr = new System.IO.StreamReader(fin);
				strTempRead = sr.ReadToEnd();
				strFileStreamText = strFileStreamText + strTempRead;
				sr.Close();
			}
			catch (System.Exception exp1)
			{
				MessageBox.Show(exp1.Message);
			}
			return strFileStreamText;
		}
	}
}

Open in new window

0
Comment
Question by:guxiyou
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 14

Accepted Solution

by:
Daniel Junges earned 500 total points
ID: 22868192
Create you project with a reference to word2000. Wen distribute you project you have to send the word2000 dlls whit him. It work then for all word versions.
0
 

Author Comment

by:guxiyou
ID: 22868371
How can I do that if I don't have a copy of word 2000 to work with?
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 22868425
hm, you have to install word 2000 on you PC and reference the dlls, or take the dlls from other PC and reference it on you project.

regards
junges
0
 

Author Comment

by:guxiyou
ID: 22868527
I assumed as much, thanks!
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
c#, datatable, aspx 4 46
Referencing a Master Template for VBA changes 3 61
Which is best Image Resizing Web service 11 31
msiexec won't run 4 14
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video shows and describes the main difference between both orientations in Microsoft Word. Viewers will understand when to use each orientation and how to get the most out of them.
Office 365 is currently available in five editions. Three of them are for business use: Office 365 Business Essentials, Office 365 Business, and Office 365 Business Premium. Two of them are for home/personal use: Office 365 Home and Office 365 Perso…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question