这可能是一个非常初学者的问题。我正在尝试创建我的第一个Windows Forms应用程序,并想通过单击表单上的按钮来创建Outlook电子邮件。
问题是有13个错误,主要是说:
严重性代码描述项目文件行抑制状态 错误CS0246找不到类型或名称空间名称'Outlook' (您是否缺少using指令或程序集引用?) 机器v.0.0.1 C:\ Users \ PC \ source \ repos \ Offer机器v.0.0.1 \ Offer 机器v.0.0.1 \ Form1.cs 29有效
我已添加对项目的引用:
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Offer_machine_v._0._0._1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
List<string> lstAllRecipients = new List<string>();
//Below is hardcoded - can be replaced with db data
lstAllRecipients.Add("sanjeev.kumar@testmail.com");
lstAllRecipients.Add("chandan.kumarpanda@testmail.com");
Outlook.Application outlookApp = new Outlook.Application();
Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMailItem.GetInspector;
// Thread.Sleep(10000);
// Recipient
Outlook.Recipients oRecips = (Outlook.Recipients)oMailItem.Recipients;
foreach (String recipient in lstAllRecipients)
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
oRecip.Resolve();
}
//Add CC
Outlook.Recipient oCCRecip = oRecips.Add("THIYAGARAJAN.DURAIRAJAN@testmail.com");
oCCRecip.Type = (int)Outlook.OlMailRecipientType.olCC;
oCCRecip.Resolve();
//Add Subject
oMailItem.Subject = "Test Mail";
// body, bcc etc...
//Display the mailbox
oMailItem.Display(true);
}
catch (Exception objEx)
{
Response.Write(objEx.ToString());
}
}
private void Label1_Click(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:1)
您没有在代码中添加适当的用法。您需要添加:
using Microsoft.Office.Interop.Outlook;
没有这一行,您应该在Interop库中的每个对象之前键入完整的名称空间。使用该功能后,您可以删除所有来自互操作对象的Outlook.
。但是创建主Application对象的对象需要完整的命名空间,以避免与Winforms中定义的Application类冲突。
Microsoft.Office.Interop.Outlook.Application outlookApp =
new Microsoft.Office.Interop.Outlook.Application();
_MailItem oMailItem = (_MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
Inspector oInspector = oMailItem.GetInspector;
..... and so on ....
答案 1 :(得分:1)
似乎您已两次将Outlook互操作性添加到项目“引用”中。
对于错误消息,您只需要向Outlook名称空间添加别名:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
此外,您可能会发现C# app automates Outlook (CSAutomateOutlook)示例项目很有帮助。