在电子邮件应用程序中询问凭据

Ask for credentials in email application

我需要在 visual studio 中创建一个应用程序来检索收件箱、从交换电子邮件帐户发送的消息和附件,以及能够标记为已读和删除所述消息(类似 outlook 的如果愿意,请申请)。

我有从 outlook 检索收件箱和附件的代码,但我需要它与 outlook 分开,或者至少我需要它能够在向我显示消息之前询问凭据。这是我的代码:

Outlook.Application Application = new Outlook.Application();
Outlook.NameSpace OutlookNameSpace =  Application.GetNamespace("MAPI");
Outlook.MAPIFolder inbox = OutlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
items = inbox.Items;

//Fills a listbox with the inbox messages
public void fillInboxListBox()
{    
    for (int i = 1; i <= inbox.Items.Count; i++)
    {
       //lsbxMessages is a ListBox control 
       lsbxMessages.Items.Add(((Outlook.MailItem)inbox.Items[i]).Subject);
    }                
}

//When an item on the listbox is selected, it loads the mail on a separate rich text box
private void lsbxMessages_SelectedIndexChanged(object sender, EventArgs e)
{
     //lblSubject is a label where I put the subject of the message
     lblSubject.Text = ((Outlook.MailItem)inbox.Items[(lsbxMessages.SelectedIndex + 1)]).Subject;

     //lblSender this is where I put the sender name and email adress         
     lblSender.Text = ((Outlook.MailItem)inbox.Items[(lsbxMessages.SelectedIndex + 1)]).SenderName + " <" + ((Outlook.MailItem)inbox.Items[(lsbxMessages.SelectedIndex + 1)]).SenderEmailAddress + ">";

     //I put the body of the email in a richtextbox         
     rtbBody.Text = ((Outlook.MailItem)inbox.Items[(lsbxMessages.SelectedIndex + 1)]).Body;

     //lblDateSent shows the date the message was sent
     lblDateSent.Text = ((Outlook.MailItem)inbox.Items[(lsbxMessages.SelectedIndex + 1)]).SentOn.ToString();

     //rtbReceiver is a rich text box where I show all the adresses the email was sent to
     rtbReceiver.Text = ((Outlook.MailItem)inbox.Items[(lsbxMessages.SelectedIndex + 1)]).To;
}

知道如何询问用户名和密码吗?

你可以通过任何你想设计的对话框来询问,然后你必须通过NameSpace.LogOn方法将参数传递给Outlook。默认情况下,您将打开当前用户的默认配置文件。

这是一个很好的教程(虽然它只显示登录默认配置文件而不要求输入用户名,添加您自己的对话框以获取 username/password 是微不足道的):

https://msdn.microsoft.com/en-us/library/office/ff462097.aspx

https://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.outlook._namespace.logon.aspx

同样重要的是要注意,如果 Outlook 已经是 运行,您将无法创建另一个 Outlook 实例,您必须获取 运行 应用程序的一个实例。 (好吧,你可以创建另一个 "instance",但它不会创建新进程,它将使用现有进程和加载的配置文件)。 即使那样我也不认为你一次可以加载多个配置文件。