简体   繁体   English

C# 如何从 C# 控制台应用程序以编程方式访问共享 Outlook/Exchange 邮箱以将电子邮件从收件箱移动到另一个文件夹

[英]C# How to access a shared outlook/exchange mailbox programmatically from a C# console application to move emails from inbox to another folder

I need to write a console application that essentially will:我需要编写一个控制台应用程序,它基本上将:

  1. Access a group/shared mailbox's inbox.访问群组/共享邮箱的收件箱。
  2. Select all emails older than n minutes.选择所有超过 n 分钟的电子邮件。
  3. Move the selected emails to another folder "AgedEmails".将选定的电子邮件移动到另一个文件夹“AgedEmails”。

So far the program I wrote works well connecting to my email account, even not passing credentials.到目前为止,我编写的程序可以很好地连接到我的电子邮件帐户,甚至没有传递凭据。
The challenge is to access the shared emailbox not mine.挑战是访问不是我的共享邮箱。 The program will run in a server on a frequency set in Windows task scheduler.该程序将以 Windows 任务调度程序中设置的频率在服务器中运行。 I have read many postings where the problem is the same I have, but could not find a solution that works.我已经阅读了许多帖子,其中的问题与我的问题相同,但找不到有效的解决方案。 I have tried the nameSpace.Logon method but it always connects to my employee's email account.我尝试了 nameSpace.Logon 方法,但它总是连接到我员工的电子邮件帐户。

These are the many ways I tried to login to the shared email account (none work): outlookNameSpace.Logon("mailboxname@company.com", "", true, true);这些是我尝试登录共享电子邮件帐户的多种方式(无效):outlookNameSpace.Logon("mailboxname@company.com", "", true, true); outlookNameSpace.Logon("mailboxname@company.com", "theRealPassword");, and this is how I try to get a handle into the inbox: inboxFolder = outlookNameSpace.Folders["mailboxname@company.com"].Folders["Inbox"]; outlookNameSpace.Logon("mailboxname@company.com", "theRealPassword");,这就是我尝试获取收件箱句柄的方式:inboxFolder = outlookNameSpace.Folders["mailboxname@company.com"].Folders["收件箱"];

I am looking for some one to put me in the right direction to achieve the goal.我正在寻找一个能让我朝着正确的方向实现目标的人。 This application will run unattended.此应用程序将在无人值守的情况下运行。

Thanks in advance for your support.预先感谢您的支持。 Here is the source code:这是源代码:

static async Task MoveEmailsAsync()
{
 StreamWriter logFile = new StreamWriter(path, append: true);
 Application outLookApplication = null;
 NameSpace outlookNameSpace = null;
 MAPIFolder inboxFolder = null;
 MAPIFolder sourceFolder = null;
 MAPIFolder testFolder = null;
 Items mailItems = null;

 string sSourceFolder = ConfigurationManager.AppSettings["SourceFolder"];
 string destinationFolder = ConfigurationManager.AppSettings["DestinationFolder"];

 try
 {
   int minutesAged = Convert.ToInt16(ConfigurationManager.AppSettings["MinutesAged"]);
   DateTime age = DateTime.Now;
   outLookApplication = new Application();
   outlookNameSpace = outLookApplication.GetNamespace("MAPI");
   inboxFolder = outlookNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
   sourceFolder = inboxFolder.Folders[sSourceFolder.ToString()];
   testFolder = inboxFolder.Folders[destinationFolder.ToString()];
   mailItems = sourceFolder.Items;
   string from = null;
   string subject = null;
   int counter = mailItems.Count;
   int i = 0;
   for (int k = counter; k >= 1; k--)
    {
      try
       {
        i++;
        if (true)  //this condition will be removed
         {
           from = null;
           subject = null;
           Microsoft.Office.Interop.Outlook.MailItem mailitem = (Microsoft.Office.Interop.Outlook.MailItem)mailItems[k];
           TimeSpan ts = DateTime.Now - mailitem.ReceivedTime;
           if (ts.TotalMinutes > minutesAged)
            {
              if (!((mailitem.SenderEmailAddress == null) || (mailitem.SenderEmailAddress == "")))
               {
                from = mailitem.SenderEmailAddress.ToString();
               }
              if (!((mailitem.Subject == null) || (mailitem.Subject == "")))
               {
                subject = mailitem.Subject;
               }
              await logFile.WriteLineAsync(i + ". From: " + from + "  - Subject: " + subject);
              mailitem.Move(testFolder);
            }
         }
       }
      catch (Exception e)
       {
        await logFile.WriteLineAsync("Exception caught: " + e.ToString());
       }
 }
 await logFile.WriteLineAsync(DateTime.Now.ToString() + " - End of Job.");
}
 catch (Exception e)
  {
   await logFile.WriteLineAsync("Exception caught: " + e.ToString());
  }
 logFile.Flush();
 logFile.Close();
 }
}

Firstly, Namespace.Logon takes the name of an existing profile (as shown in Control Panel | Mail | Show Profiles), not an address of a mailbox.首先, Namespace.Logon采用现有配置文件的名称(如控制面板 | 邮件 | 显示配置文件中所示),而不是邮箱地址。

Secondly, to open a folder from another user's mailbox, replace the GetDefaultFolder call with Namespace.CreateRecipient / Namespace.GetSharedDefaultFolder其次,要从另一个用户的邮箱打开文件夹,请将GetDefaultFolder调用替换为Namespace.CreateRecipient / Namespace.GetSharedDefaultFolder

Answers to your questions don't make any sense due to the following statement:由于以下陈述,您的问题的答案没有任何意义:

The program will run in a server on a frequency set in Windows task scheduler.该程序将以 Windows 任务调度程序中设置的频率在服务器中运行。

That is the key statement in your post because MS states the following for such scenarios:这是您帖子中的关键声明,因为 MS 针对此类情况说明了以下内容:

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment. Microsoft 目前不推荐也不支持任何无人值守、非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)的 Microsoft Office 应用程序自动化,因为 Office 可能表现出不稳定的行为和/或在此环境中运行 Office 时出现死锁。

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution.如果您正在构建在服务器端上下文中运行的解决方案,您应该尝试使用已确保无人值守执行安全的组件。 Or, you should try to find alternatives that allow at least part of the code to run client-side.或者,您应该尝试找到允许至少部分代码在客户端运行的替代方案。 If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully.如果您使用来自服务器端解决方案的 Office 应用程序,该应用程序将缺少许多成功运行所需的功能。 Additionally, you will be taking risks with the stability of your overall solution.此外,您将承担整体解决方案稳定性的风险。

Read more about that in the Considerations for server-side Automation of Office article.Office 服务器端自动化的注意事项文章中阅读有关此内容的更多信息。

If you deal with Exchange accounts you may consider using EWS instead, see Explore the EWS Managed API, EWS, and web services in Exchange for more information.如果您处理 Exchange 帐户,则可以考虑改用 EWS,请参阅探索 Exchange 中的 EWS 托管 API、EWS 和 Web 服务以获取更多信息。 In case of Office365 consider using the Graph API, see Use the Microsoft Graph API .如果是 Office365,请考虑使用 Graph API,请参阅使用 Microsoft Graph API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 提取某天从共享收件箱,C#中的Exchange 2016 EWS的未知文件夹中收到的电子邮件 - Fetch emails received on certain day from non-Well-known folder in shared inbox, Exchange 2016 EWS in C# 从Outlook中的共享文件夹中使用C#读取电子邮件 - Reading emails with C# from shared folder in Outlook C# 如何从 Outlook 的共享邮箱发送邮件并将其保存在已发送文件夹中 - C# How to send mail from Outlook's Shared Mailbox and keep it in Sent folder there 如何从Outlook收件箱下载Excel附件并将数据保存到C#控制台应用程序中的sql服务器? - How to download an excel attachment from outlook inbox and save the data to sql server in C# Console Application? 从Outlook C#中的“共享邮箱”获取用户定义的类别 - Get user defined categories from Shared Mailbox in Outlook C# 如何从Clutter Outlook文件夹C#中读取电子邮件 - How to read emails from Clutter outlook folder C# 如何以编程方式从C#Web应用程序在Exchange 2007服务器上添加邮箱别名? - How to programmatically add mailbox alias on an Exchange 2007 server from C# web app? c#以编程方式从Exchange服务器读取电子邮件 - c# programmatically reading emails from the Exchange server c#forward来自Outlook收件箱的电子邮件 - c# forward Email from Outlook inbox 使用C#从Outlook文件夹中删除电子邮件 - Delete Emails from Outlook Folder Using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM