允许使用 ews 模拟

Allow impersonation using ews

我正在尝试用 C# 创建一个程序,它应该能够在其他人的 Outlook 日历中创建约会。我有代码可以在我自己的日历中创建约会。我在 Google 上搜索,发现我应该使用模拟。所以我添加了行:

service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress);

这是我的代码:

private void button2_Click(object sender, EventArgs e) {
try{
    ExchangeService service = new ExchangeService();
    service.UseDefaultCredentials = true;   
    service.Credentials = new WebCredentials("Test@domain.com", "password");
    service.AutodiscoverUrl("Test@domain.com", adAutoDiscoCallBack);
    service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "Test2@domain.com");

    Appointment appointment = new Appointment(service);
    // Set the properties on the appointment object to create the appointment.
    appointment.Subject = "Tennis lesson";
    appointment.Body = "Focus on backhand this week.";
    appointment.Start = DateTime.Now.AddDays(2);
    appointment.End = appointment.Start.AddHours(1);
    appointment.Location = "Tennis club";
    appointment.ReminderDueBy = DateTime.Now;

    // Save the appointment to your calendar.
    appointment.Save(SendInvitationsMode.SendToNone);

    // Verify that the appointment was created by using the appointment's item ID.
    Item item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject));
}
}catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

internal static bool adAutoDiscoCallBack(string redirectionUrl) {
    // The default for the validation callback is to reject the URL.
    bool result = false;

    Uri redirectionUri = new Uri(redirectionUrl);

    // Validate the contents of the redirection URL. In this simple validation
    // callback, the redirection URL is considered valid if it is using HTTPS
    // to encrypt the authentication credentials. 
    if (redirectionUri.Scheme == "https") {
        result = true;
    }

    return result;
}

问题是我一直收到这个错误“"The SMTP-address has no mailbox associated with it."

是不是服务器不允许模拟?如果是这样我怎么允许它? 希望有人能帮忙。

Ps:抱歉英语不好

一些建议如果这是 Office365 或 Exchange 2013,您首先需要您希望访问的邮箱的 PrimarySMTP 地址,例如

String MailboxToAccess = "PriamarySMTP@domain.com";

注意一些租户的 SMTP 和 UPN/Logon 是相同的,但情况并非总是如此。

这就是您要模拟的用户,例如

service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, MailboxToAccess);

您还应该在 X-AnchorMailbox header https://docs.microsoft.com/en-us/archive/blogs/webdav_101/best-practices-ews-authentication-and-access-issues 中添加例如

service.HttpHeaders.Add("X-AnchorMailbox", MailboxToAccess);

此外,当您去保存约会时,使用 FolderId class 和邮箱过载以确保您点击正确的邮箱,例如

FolderId CalendarFolderId = new FolderId(WellKnownFolderName.Calendar, MailboxToAccess);
appointment.Save(CalendarFolderId,SendInvitationsMode.SendToNone);

干杯 格伦