เชื่อมต่อกับ Exchange Server ด้วย EWS และ IMAP

Contents
[ ]

เพื่อเชื่อมต่อกับ Exchange server 2007, 2010 และ 2013 โดยใช้ Exchange Web Service, Aspose.Email มี IEWSClient อินเทอร์เฟซที่ทำงานตาม EWSClient คลาส. เมธอด EWSClient.GetEWSClient เมธอดสร้างอินสแตนซ์และคืนค่า IEWSClient ออบเจกต์ที่ใช้ต่อไปเพื่อทำการดำเนินการที่เกี่ยวกับกล่องเมล Exchange และโฟลเดอร์อื่น ๆ บทความนี้แสดงวิธีสร้างอินสแตนซ์ของออบเจกต์ IEWSClient.

เชื่อมต่อกับ Exchange Server ด้วย EWS

ตัวอย่างโค้ดต่อไปนี้แสดงวิธีสร้างการเชื่อมต่อโดยใช้ Exchange Web Service (EWS):

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
private static IEWSClient GetExchangeEWSClient()
{
    const string mailboxUri = "https://outlook.office365.com/ews/exchange.asmx";
    const string domain = @"";
    const string username = @"username@ASE305.onmicrosoft.com";
    const string password = @"password";
    NetworkCredential credentials = new NetworkCredential(username, password, domain);
    IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credentials);
    return client;
}

เพิ่ม Header กำหนดเองในการเริ่มต้น EWSClient

ในสถานการณ์ที่ต้องการ header เฉพาะระหว่างการเริ่มต้นคลไอเอนท์, เช่น header X-AnchorMailbox ใน EWS, ใช้วิธีการโอเวอร์โหลดต่อไปนี้เพื่อเพิ่ม header แบบกำหนดเองเมื่อสร้างอินสแตนซ์ของ IEWSClient:

  • IEWSClient GetEWSClient(string mailboxUri, ICredentials credentials, WebProxy proxy, Dictionary headers)

  • async Task GetEwsClientAsync(string mailboxUri, ICredentials credentials, WebProxy proxy, CancellationToken cancellationToken , Dictionary headers)

ตัวอย่างโค้ดด้านล่างแสดงวิธีกำหนดค่าและเริ่มต้น IEWSClient พร้อมใช้ HTTP header แบบกำหนดเอง:

var headers = new Dictionary<string, string>();
headers.Add("X-AnchorMailbox", smtpExampleAddress);
IEWSClient client = EWSClient.GetEWSClient(HttpsExampleCom, new OAuthNetworkCredential("UserName", "Token"), null, headers);

เชื่อมต่อกับ Exchange Server ด้วย IMAP

Microsoft Exchange Server สนับสนุนโปรโตคอล IMAP สำหรับการเข้าถึงรายการในกล่องจดหมาย. ใช้ Aspose.Email ImapClient คลาสเพื่อเชื่อมต่อกับ Exchange Server ด้วยโปรโตคอล IMAP ข้อมูลเพิ่มเติมเกี่ยวกับ ImapClient คลาส ก่อนแรกให้แน่ใจว่า IMAP service เปิดใช้งานสำหรับ Exchange Server ของคุณ:

  1. เปิด Control Panel.
  2. ไปที่ Administrator Tools แล้วเลือก Services.
  3. ตรวจสอบสถานะของบริการ Microsoft Exchange IMAP4.
  4. หากยังไม่ได้ทำงาน ให้เปิดใช้งาน/เริ่มต้นมัน.

โค้ดส่วนต่อไปนี้จะแสดงวิธีเชื่อมต่อและแสดงรายการข้อความจากโฟลเดอร์ Inbox ของ Microsoft exchange server โดยใช้โปรโตคอล IMAP.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect to Exchange Server using ImapClient class
ImapClient imapClient = new ImapClient("ex07sp1", "Administrator", "Evaluation1");
imapClient.SecurityOptions = SecurityOptions.Auto;

// Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox);

// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
foreach (ImapMessageInfo msgInfo in msgCollection)
{
    Console.WriteLine(msgInfo.Subject);
}
// Disconnect from the server
imapClient.Dispose();

โค้ดส่วนต่อไปนี้จะแสดงวิธีใช้ SSL.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
public static void Run()
{            
    // Connect to Exchange Server using ImapClient class
    ImapClient imapClient = new ImapClient("ex07sp1", 993, "Administrator", "Evaluation1", new RemoteCertificateValidationCallback(RemoteCertificateValidationHandler));
    imapClient.SecurityOptions = SecurityOptions.SSLExplicit;

    // Select the Inbox folder
    imapClient.SelectFolder(ImapFolderInfo.InBox);

    // Get the list of messages
    ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
    foreach (ImapMessageInfo msgInfo in msgCollection)
    {
        Console.WriteLine(msgInfo.Subject);
    }
    // Disconnect from the server
    imapClient.Dispose();   
}

// Certificate verification handler
private static bool RemoteCertificateValidationHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true; // ignore the checks and go ahead
}

หลังจากเชื่อมต่อกับ Exchange server ด้วย IMAP และรับ IMapMessageInfoCollection, คุณสามารถรับ MessageInfo อ็อบเจ็กต์. ตัวอย่างโค้ดต่อไปนี้แสดงวิธีใช้หมายเลขลำดับของ MessageInfo อ็อบเจ็กต์เพื่อบันทึกข้อความเฉพาะ.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox);
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
foreach (ImapMessageInfo msgInfo in msgCollection)
{
    // Fetch the message from inbox using its SequenceNumber from msgInfo
    MailMessage message = imapClient.FetchMessage(msgInfo.SequenceNumber);

    // Save the message to disc now
    message.Save(dataDir + msgInfo.SequenceNumber + "_out.msg", SaveOptions.DefaultMsgUnicode);
}

การตั้งค่าโปรโตคอลการเข้ารหัสที่ต้องการ

EWS ใช้โปรโตคอลการส่งข้อมูล HTTPS สำหรับการดำเนินการที่สนับสนุน. การเข้ารหัสมาจากโปรโตคอล SSL/TLS. โปรโตคอลเหล่านี้ถูกนำมาใช้โดย .NET framework และอาจแตกต่างกันขึ้นกับเวอร์ชันปัจจุบันของ .NET framework.

เพื่อกำหนดเวอร์ชัน SSL/TLS ใช้โค้ดต่อไปนี้:

var client = new ImapClient("some.host");
client.SupportedEncryption = EncryptionProtocols.Tls13;

หรือ

var client = new ImapClient("some.host");
client.SetSupportedEncryptionUnsafe(EncryptionProtocols.Tls13);

หมายเหตุ, หาก EncryptionProtocol ที่ระบุไม่ได้รับการสนับสนุนโดยเวอร์ชันปัจจุบันของ .NET framework, SupportedEncryption พร็อพเพอร์ตี้ทำให้การเข้ารหัสระดับต่ำลงเป็นระดับที่สนับสนุนและ SetSupportedEncryptionUnsafe เมธอดโยนข้อยกเว้น.

เชื่อมต่อกับ Exchange Server โดยใช้ Modern Authentication

Modern Authentication ตอนนี้เปิดใช้งานโดยค่าเริ่มต้นสำหรับ tenant Microsoft 365/Azure ใหม่ทั้งหมด เนื่องจากโปรโตคอลนี้ปลอดภัยกว่าการใช้ Basic Authentication ที่เลิกใช้แล้ว.

Modern Authentication อยู่บน Active Directory Authentication Library และ OAuth 2.0. มันใช้โทเค็นที่มีอายุจำกัด, และแอปพลิเคชันไม่จัดเก็บข้อมูลประจำตัวผู้ใช้.

การตั้งค่าก่อนใช้งาน

เพื่อใช้ Modern Authentication, ตรวจสอบให้แน่ใจว่ามันเปิดใช้งาน. อย่างไรก็ตาม, สำหรับ tenant ที่สร้างก่อน 1 สิงหาคม 2017, Modern Authentication จะปิดโดยค่าเริ่มต้น. ใน ศูนย์ผู้ดูแล Microsoft 365, ไปที่ Settings > Org Settings > Modern Authentication. ใน Modern authentication flyout ที่ปรากฏ, คุณสามารถระบุโปรโตคอลที่ไม่ต้องใช้ Basic authentication อีกต่อไป. สำหรับ tenant Microsoft365 ใหม่ใน Azure, Basic Authentication จะถูกปิดโดยค่าเริ่มต้นสำหรับทุกแอปพลิเคชัน. ดังนั้น ข้อความนี้จะแสดงในส่วนนี้.

องค์กรของคุณเปิดใช้ค่าปริยายด้านความปลอดภัย, ซึ่งหมายความว่าต้องใช้การตรวจสอบสิทธิ์สมัยใหม่กับ Exchange Online และการเชื่อมต่อ Basic Authentication ถูกบล็อก. > คุณต้องปิดค่าปริยายด้านความปลอดภัยในพอร์ทัล Azure ก่อนจึงจะเปลี่ยนการตั้งค่าใด ๆ ที่นี่.

คุณสามารถเปิดการสนับสนุน Basic Auth สำหรับ tenant ได้จาก Azure พอร์ทัล, ไปที่ Azure Active Directory > Properties > Manage Security defaults > Enable Security defaults > No. สำหรับข้อมูลเพิ่มเติม, ดูที่ บทความเอกสารของ Microsoft.

การลงทะเบียนแอปกับ Azure Active Directory

จำเป็นต้องทำการลงทะเบียนแอปกับ Azure Active Directory. มีสองประเภทของสิทธิ์ที่สามารถใช้เพื่อเข้าถึงกล่องจดหมายด้วยแอปของคุณ. เลือกประเภทสิทธิ์ที่เฉพาะตามแอปที่คุณกำลังสร้าง:

  • แอปที่ใช้ สิทธิ์แบบมอบหมาย มีผู้ใช้ที่ลงชื่อเข้าใช้อยู่. กล่าวคือ เมื่อคุณเชื่อมต่อกับบริการ จะมีหน้าต่างโต้ตอบขอชื่อผู้ใช้และรหัสผ่าน. แอปไม่สามารถมีสิทธิ์มากกว่าผู้ใช้ที่ลงชื่อเข้าใช้ได้.
  • แอปที่ใช้ สิทธิ์แอปพลิเคชัน ทำงานโดยไม่มีผู้ใช้ที่ลงชื่อเข้าใช้อยู่. ตัวอย่างเช่น เป็นแอปที่ทำงานเป็นบริการพื้นหลังหรือ daemon. เฉพาะผู้ดูแลระบบเท่านั้นที่สามารถให้ความยินยอมต่อสิทธิ์แอปพลิเคชัน.

นอกจากนี้ ดูที่ บทความเอกสารของ Microsoft สำหรับข้อมูลเพิ่มเติม.

ขั้นตอนการลงทะเบียนขึ้นอยู่กับประเภทของสิทธิ์ที่เลือก. เพื่อลงทะเบียนแอปของคุณ ดูที่ บทความเอกสารของ Microsoft.

ใช้การตรวจสอบสิทธิ์สมัยใหม่กับ EWSClient

หลังจากลงทะเบียนแอปพลิเคชัน เราสามารถมุ่งเน้นที่การเขียนโค้ด ซึ่งจะประกอบด้วยส่วนต่อไปนี้:

  • รับโทเค็นการอนุญาต.
  • ใช้โทเค็นเพื่อยืนยันตัวตน.

รับโทเค็นการอนุญาต

เพื่อรับโทเค็น เราจะใช้ Microsoft Authentication Library (MSAL) สำหรับ .NET.

ต่อไปนี้คือขั้นตอนการรับโทเค็นการอนุญาต.

  • เพิ่ม แพคเกจ NuGet Microsoft.Identity.Client ซึ่งประกอบด้วยไบนารีของ MSAL.NET.
  • สร้างคลาส AccessParameters เพื่อเก็บข้อมูลประจำตัว.
  • สร้างเมธอดที่รับพารามิเตอร์การเข้าถึงและใช้ MSAL.NET เพื่อรับโทเค็นการเข้าถึง.

ตัวอย่างโค้ดต่อไปนี้จะขึ้นอยู่กับประเภทของการตรวจสอบสิทธิ์ที่เลือก.

รับโทเค็นด้วยการตรวจสอบสิทธิ์แบบมอบหมาย

public class AccessParameters
{
    public string TenantId { get; set; }
    public string ClientId { get; set; }
    public string RedirectUri { get; set; } = "http://localhost";
    public string[] Scopes { get; set; } = { "https://outlook.office365.com/EWS.AccessAsUser.All" };
}

public static async Task<string> GetAccessToken(AccessParameters accessParameters)
{
    var pca = PublicClientApplicationBuilder
                            .Create(accessParameters.ClientId)
                            .WithTenantId(accessParameters.TenantId)
                            .WithRedirectUri(ccessParameters.RedirectUri)
                            .Build();

    var result = await pca.AcquireTokenInteractive(accessParameters.Scopes)
        .WithUseEmbeddedWebView(false)
        .ExecuteAsync();

    return result.AccessToken;
}

รับโทเค็นด้วยการตรวจสอบสิทธิ์ของแอป

public class AccessParameters
{
    public string TenantId { get; set; }
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
    public string[] Scopes { get; set; } = { "https://outlook.office365.com/.default" };
}

public static async Task<string> GetAccessToken(AccessParameters accessParameters)
{
    var cca = ConfidentialClientApplicationBuilder
        .Create(accessParameters.ClientId)
        .WithClientSecret(accessParameters.ClientSecret)
        .WithTenantId(accessParameters.TenantId)
        .Build();

    var result = await cca.AcquireTokenForClient(accessParameters.Scopes).ExecuteAsync();

    return result.AccessToken;
}

การตรวจสอบสิทธิ์ด้วยโทเค็น

หลังจากนั้น เมื่อเราได้รับโทเค็นสำเร็จแล้ว ให้เริ่มต้น EwsClient.

ใช้โทเค็นกับการตรวจสอบสิทธิ์แบบมอบหมาย

NetworkCredential credentials = new OAuthNetworkCredential(accessToken);

using var client = EWSClient.GetEWSClient("https://outlook.office365.com/EWS/Exchange.asmx", credentials);

ใช้โทเค็นกับการตรวจสอบสิทธิ์ของแอป

// Use Microsoft365 username and access token
NetworkCredential credentials = new OAuthNetworkCredential(username, accessToken);

using var client = EWSClient.GetEWSClient("https://outlook.office365.com/EWS/Exchange.asmx", credentials);

ใช้ Modern Authentication กับไคลเอนท์ IMAP, POP หรือ SMTP

การเข้าถึง IMAP, POP, SMTP ผ่านสิทธิ์แอปพลิเคชันไม่รองรับ. กล่าวคือ รองรับเฉพาะการตรวจสอบสิทธิ์แบบมอบหมาย.

ขั้นตอนการลงทะเบียนแอปกับ Azure Active Directory ถูกกำหนด ข้างต้น.

เปิดหรือปิด IMAP, POP, SMTP AUTH ในศูนย์ผู้ดูแล Microsoft 365

  • เปิด ศูนย์ผู้ดูแล Microsoft 365 และไปที่ Users > Active users.
  • เลือกผู้ใช้, และใน flyout ที่ปรากฏ, คลิก Mail.
  • ในส่วน Email apps, คลิก Manage email apps.
  • ตรวจสอบการตั้งค่า IMAP, POP, Authenticated SMTP: ไม่เลือก = ปิดใช้งาน, เลือก = เปิดใช้งาน.
  • คลิก Save changes.

เรียกคืนโทเค็นการตรวจสอบสิทธิ์จากเซิร์ฟเวอร์โทเค็น

ตรวจสอบให้แน่ใจว่ากำหนดสโคปทั้งหมดรวมถึง URL ของทรัพยากร Outlook.

IMAP: https://outlook.office.com/IMAP.AccessAsUser.All POP: https://outlook.office.com/POP.AccessAsUser.All SMTP: https://outlook.office.com/SMTP.Send

เพื่อรับโทเค็น เราจะใช้ Microsoft Authentication Library (MSAL) สำหรับ .NET.

ต่อไปนี้คือขั้นตอนการรับโทเค็นการอนุญาต.

  • เพิ่ม แพคเกจ NuGet Microsoft.Identity.Client ซึ่งประกอบด้วยไบนารีของ MSAL.NET.
  • สร้างคลาส AccessParameters เพื่อเก็บข้อมูลประจำตัว.
  • สร้างเมธอดที่รับพารามิเตอร์การเข้าถึงและใช้ MSAL.NET เพื่อรับโทเค็นการเข้าถึง.
public class AccessParameters
{
    public string TenantId { get; set; }
    public string ClientId { get; set; }
    public string RedirectUri { get; set; } = "http://localhost";
    public string[] Scopes { get; set; } = { 
        "https://outlook.office.com/IMAP.AccessAsUser.All", 
        "https://outlook.office.com/SMTP.Send" };
}

public static async Task<string> GetAccessToken(AccessParameters accessParameters)
{
    var pca = PublicClientApplicationBuilder
                            .Create(accessParameters.ClientId)
                            .WithTenantId(accessParameters.TenantId)
                            .WithRedirectUri(ccessParameters.RedirectUri)
                            .Build();

    var result = await pca.AcquireTokenInteractive(accessParameters.Scopes)
        .WithUseEmbeddedWebView(false)
        .ExecuteAsync();

    return result.AccessToken;
}

ตรวจสอบสิทธิ์ด้วยโทเค็น

หลังจากนั้น เมื่อเราได้รับโทเค็นสำเร็จแล้ว ให้เริ่มต้น ImapClient.

var imapClient = new ImapClient(
    "outlook.office365.com", 
    993, 
    username, 
    accessToken, 
    true);

เช่นเดียวกัน, SmtpClient การเริ่มต้นจะมีลักษณะดังต่อไปนี้.

var smtpClient = new SmtpClient(
    "smtp.office365.com",
    587, 
    username,
    accessToken, 
    true);

คืนค่า Client Request ID

นี้ ReturnClientRequestId ได้เพิ่ม property เข้าไปใน EWSClient เพื่อความสะดวกของคุณในการระบุว่าควรคืนค่า client request ID ในการตอบกลับจากการเรียก Exchange Web Services (EWS) หรือไม่. client request ID คือ identifiers ที่ไม่ซ้ำกันซึ่งคุณสามารถตั้งค่าได้สำหรับแต่ละคำขอ EWS ที่ส่งจากแอปพลิเคชันของคุณ. โดยการตั้งค่า ReturnClientRequestId ตั้งค่าพร็อพเพอร์ตี้เป็น true แสดงว่าคุณต้องการให้ client request ID ถูกใส่ในการตอบกลับจากเซิร์ฟเวอร์ EWS. สิ่งนี้มีประโยชน์สำหรับการติดตามและเชื่อมโยงคำขอและการตอบกลับในสถานการณ์ที่มีการทำหลายคำขอพร้อมกันแบบอะซิงโครนัส.

ตัวอย่างโค้ดต่อไปนี้แสดงวิธีใช้พร็อพเพอร์ตี้:

using (IEWSClient client = TestUtil.CreateEWSClient(user))
{
   // Client will create random id and pass it to the server.
   // The server should include this id in request-id header of all responses.
   client.ReturnClientRequestId = true;
   
   client.LogFileName = "ews.log";
   client.GetMailboxInfo();
}

เพิ่ม X-AnchorMailbox และ Header อื่น ๆ ไปยังคำขอ EWS

Aspose.Email API อนุญาตให้เพิ่ม header ไปยังคำขอ Exchange. สามารถใช้เพื่อเพิ่ม header ไปยังคำขอ EWS สำหรับ header ต่าง ๆ ที่ใช้เพื่อวัตถุประสงค์ที่แตกต่างกัน. ตัวอย่างหนึ่งคือการเพิ่ม header X-AnchorMailbox ที่ใช้จัดการปัญหา throttling บนเซิร์ฟเวอร์ Exchange. AddHeader เมธอดของ IEWSClient ใช้เพื่อเพิ่ม header ไปยังคำขอ EWS ตามที่แสดงในตัวอย่างโค้ดต่อไปนี้.

ละเลยหรือข้ามใบรับรอง SSL ที่ไม่ถูกต้องหรือหมดอายุ

Aspose.Email สามารถจัดการใบรับรอง SSL บน Exchange Server ได้โดยใช้ทั้ง ExchangeClient และ EWSClient คลาส. หากใบรับรอง SSL หมดอายุหรือไม่ถูกต้อง Aspose.Email จะขว้างข้อยกเว้นเนื่องจากใบรับรอง SSL ไม่ถูกต้อง. หลีกเลี่ยงข้อผิดพลาดของใบรับรอง SSL โดยการละเลยโดยใช้วิธีที่ใช้ในโค้ดด้านล่าง. ลงทะเบียน callback handler ในเมธอด main() หรือ init() ของคุณและเพิ่มเมธอดด้านล่างเป็นสมาชิกของคลาส.