简介
本文介绍如何使用 Microsoft Outlook 2002 对象库或 Microsoft Office Outlook 2003 对象库通过 Microsoft Visual C# 发送 HTML 格式C#。
更多信息
若要使用 Outlook 2002 对象库或 Outlook 2003 对象库通过 Microsoft Visual C# 发送 HTML 格式的邮件,请执行以下步骤:
-
在 Microsoft Visual Studio .NET 或 Microsoft Visual Studio 2005 中,创建新的控制台应用程序项目:
-
在"文件"菜单上,指向"新建",然后单击"Project"。
-
在Project类型"下,单击"visual C# Projects"。
注意 在 Microsoft Visual C# 2005 中,单击"visual C#"Project类型"。 -
在 "模板"下,单击" 控制台应用程序"。
-
单击“确定”。 默认情况下,将创建名为 Class1.cs 的文件。
注意 在 Microsoft Visual C# 2005 中,默认情况下会创建 Program.cs。
-
-
添加对 Outlook 2002 对象库或 Outlook 2003 对象库的引用。 为此,请按照下列步骤操作:
-
在"Project"菜单上,单击"添加引用"。
-
单击 "COM" 选项卡。
-
在"COM"选项卡上,如果使用的是 Outlook 2003,请单击"Microsoft Outlook 11.0 对象库",如果使用的是 Outlook 2002,请单击"Microsoft Outlook 10.0 对象库"。
-
单击" 选择"。
注意 在 Visual C# 2005 中,不需要单击"选择 "。 -
在" 添加引用" 对话框中,单击"确定 "。
注意 如果收到消息,要求为所选库生成包装器,请单击"是 "。
-
-
在 Class1.cs 代码窗口中,将所有现有代码替换为以下代码:
using System;
using System.Reflection; // to use Missing.Value
// TO DO: If you use the Microsoft Outlook 11.0 Object Library, uncomment the following line.
// using Outlook = Microsoft.Office.Interop.Outlook;
namespace SendHTMLMail
{
public class Class1
{
public static int Main(string[] args)
{
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Get the NameSpace and Logon information.
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Alternate logon method that uses a specific profile.
// TODO: If you use this logon method,
// change the profile name to an appropriate value.
//oNS.Logon("YourValidProfile", Missing.Value, false, true);
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set the subject.
oMsg.Subject = "Send Using OOM in C#";
// Set HTMLBody.
String sHtml;
sHtml = "<HTML>\n" +
"<HEAD>\n" +
"<TITLE>Sample GIF</TITLE>\n" +
"</HEAD>\n" +
"<BODY><P>\n" +
"<h1><Font Color=Green>Inline graphics</Font></h1></P>\n" +
"</BODY>\n" +
"</HTML>";
oMsg.HTMLBody = sHtml;
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// TODO: Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("email address");
oRecip.Resolve();
// Send.
oMsg.Send();
// Log off.
oNS.Logoff();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oNS = null;
oApp = null;
}
// Simple error handling.
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
// Default return value.
return 0;
}
}
} -
在此代码中,在看到"要执行"注释时进行任何必要的更改。
-
按 F5 生成,然后运行程序。
-
验证电子邮件已发送且已收到。
参考
有关详细信息,请访问 MSDN 网站Microsoft 开发人员网络 (以下) MSDN:
http://msdn2.microsoft.com/en-us/library/aa188489 (office.10) .aspx有关 Outlook 2002 电子邮件安全功能以及这些功能如何影响自定义解决方案的更多信息,请单击以下文章编号,查看 Microsoft 知识库中的文章:
290500 说明 2002 年 2 月中开发人员Outlook安全功能