วิธีสร้างการเชื่อมต่อ IMAP ใน C#

แสดงรายการส่วนขยายของเซิร์ฟเวอร์ IMAP

ของ Aspose.Email ImapClient ทำให้คุณสามารถดึงส่วนขยายของเซิร์ฟเวอร์ที่เซิร์ฟเวอร์รองรับ เช่น IDLE, UNSELECT, QUOTA ฯลฯ ซึ่งช่วยระบุว่ามีส่วนขยายดังกล่าวหรือไม่ก่อนใช้ไคลเอนต์สำหรับฟังก์ชันนั้น The GetCapabilities() เมธอดคืนค่าประเภทส่วนขยายที่รองรับในรูปแบบอาร์เรย์ของสตริง ตัวอย่างโค้ดต่อไปนี้แสดงวิธีเรียกคืนส่วนขยาย.

การเชื่อมต่อ IMAP มาตรฐาน

นี้ ImapClient คลาสนี้อนุญาตให้แอปพลิเคชันจัดการกล่องเมล IMAP ด้วยโปรโตคอล IMAP. ImapClient คลาสนี้ใช้เชื่อมต่อกับเซิร์ฟเวอร์เมล IMAP และจัดการอีเมลในโฟลเดอร์ IMAP เพื่อเชื่อมต่อกับเซิร์ฟเวอร์ IMAP

  1. สร้างอินสแตนซ์ของ ImapClient คลาส.
  2. ระบุ hostname, username, และ password ใน คอนสตรัคเตอร์ ImapClient.

หมายเหตุ ข้อจำกัดรหัสผ่านต้องตรงกับความต้องการของเซิร์ฟเวอร์ ลูกค้าอีเมลไม่ได้เพิ่มข้อจำกัดรหัสผ่าน

เมื่อ ImapClient เมื่ออินสแตนซ์เริ่มต้น การเรียกใช้งานใด ๆ ต่อไปโดยใช้อินสแตนซ์นี้จะเชื่อมต่อกับเซิร์ฟเวอร์ โค้ดตัวอย่างต่อไปนี้แสดงวิธีเชื่อมต่อกับเซิร์ฟเวอร์ IMAP โดยใช้ขั้นตอนข้างต้น.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an imapclient with host, user and password
ImapClient client = new ImapClient("localhost", "user", "password");

การเชื่อมต่อ IMAP ที่เปิดใช้งาน SSL

การเชื่อมต่อกับเซิร์ฟเวอร์ IMAP อธิบายวิธีเชื่อมต่อกับเซิร์ฟเวอร์ IMAP ในสี่ขั้นตอนง่าย ๆ:

  1. สร้างอินสแตนซ์ของ ImapClient คลาส.
  2. ระบุ hostname, username, และ password.
  3. ระบุพอร์ต.
  4. ระบุตัวเลือกความปลอดภัย.

กระบวนการเชื่อมต่อกับเซิร์ฟเวอร์ IMAP ที่เปิดใช้งาน SSL จะคล้ายกันแต่ต้องตั้งค่าอีกหลายคุณสมบัติ:

โค้ดตัวอย่างต่อไปนี้แสดงวิธี

  1. ตั้งค่าชื่อผู้ใช้, รหัสผ่าน, และพอร์ต.
  2. ตั้งค่าตัวเลือกความปลอดภัย
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance of the ImapClient class
ImapClient client = new ImapClient("imap.domain.com", 993, "user@domain.com", "pwd");
            
// Set the security mode to implicit
client.SecurityOptions = SecurityOptions.SSLImplicit;

การตั้งค่าการเชื่อมต่อพร็อกซี

เชื่อมต่อกับเซิร์ฟเวอร์ผ่าน Proxy

เซิร์ฟเวอร์พร็อกซีมักใช้ในการสื่อสารกับภายนอก ในกรณีดังกล่าว ไคลเอนต์อีเมลไม่สามารถสื่อสารผ่านอินเทอร์เน็ตได้หากไม่ได้ระบุที่อยู่พร็อกซี Aspose.Email ให้การสนับสนุนเวอร์ชัน 4, 4a และ 5 ของโปรโตคอล SOCKS Proxy บทความนี้ให้ตัวอย่างการเข้าถึงกล่องจดหมายโดยใช้เซิร์ฟเวอร์เมลพร็อกซี เพื่อเข้าถึงกล่องจดหมายผ่านเซิร์ฟเวอร์พร็อกซี:

  1. Initialize SocksProxy ด้วยข้อมูลที่ต้องการ ได้แก่ ที่อยู่พร็อกซี, พอร์ต, และเวอร์ชันของ SOCKS
  2. Initialize ImapClient ด้วยที่อยู่โฮสต์, ชื่อผู้ใช้, รหัสผ่าน และการตั้งค่าอื่น ๆ
  3. ตั้งค่าของไคลเอนต์ SocksProxy คุณสมบัติของไคลเอนต์ไปยัง SocksProxy วัตถุที่สร้างขึ้นด้านบน

โค้ดตัวอย่างต่อไปนี้แสดงวิธีดึงกล่องจดหมายผ่านเซิร์ฟเวอร์พร็อกซี

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect and log in to IMAP and set SecurityOptions
ImapClient client = new ImapClient("imap.domain.com", "username", "password");
client.SecurityOptions = SecurityOptions.Auto;
            
string proxyAddress = "192.168.203.142"; // proxy address
int proxyPort = 1080; // proxy port
SocksProxy proxy = new SocksProxy(proxyAddress, proxyPort, SocksVersion.SocksV5);

// Set the proxy
client.Proxy = proxy;
           
try
{
    client.SelectFolder("Inbox");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

เชื่อมต่อกับเซิร์ฟเวอร์ผ่าน HTTP Proxy

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
HttpProxy proxy = new HttpProxy("18.222.124.59", 8080);
using (ImapClient client = new ImapClient("imap.domain.com", "username", "password"))
{
    client.Proxy = proxy;
    client.SelectFolder("Inbox");
}

การเชื่อมต่อแบบอ่านอย่างเดียว

นี้ ImapClient คลาสให้ ReadOnly คุณสมบัติที่เมื่อกำหนดเป็น true จะหมายถึงไม่ให้ทำการเปลี่ยนแปลงใด ๆ กับภาวะถาวรของกล่องจดหมาย ตัวอย่างโค้ดต่อไปนี้แสดงการใช้ ImapClient.ReadOnly คุณสมบัติ จะรับจำนวนข้อความที่ยังไม่ได้อ่าน แล้วดึงข้อความหนึ่งข้อความและรับจำนวนข้อความที่ยังไม่ได้อ่านอีกครั้งในโหมดอ่านอย่างเดียว จำนวนข้อความที่ยังไม่ได้อ่านยังคงเท่าเดิมแสดงว่าภาวะถาวรของกล่องจดหมายไม่ได้เปลี่ยนแปลง

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
ImapClient imapClient = new ImapClient();
imapClient.Host = "<HOST>";
imapClient.Port = 993;
imapClient.Username = "<USERNAME>";
imapClient.Password = "<PASSWORD>";
imapClient.SupportedEncryption = EncryptionProtocols.Tls;
imapClient.SecurityOptions = SecurityOptions.SSLImplicit;

ImapQueryBuilder imapQueryBuilder = new ImapQueryBuilder();
imapQueryBuilder.HasNoFlags(ImapMessageFlags.IsRead); /* get unread messages. */
MailQuery query = imapQueryBuilder.GetQuery();

imapClient.ReadOnly = true;
imapClient.SelectFolder("Inbox");
ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages(query);
Console.WriteLine("Initial Unread Count: " + messageInfoCol.Count());
if (messageInfoCol.Count() > 0)
{
    imapClient.FetchMessage(messageInfoCol[0].SequenceNumber);

    messageInfoCol = imapClient.ListMessages(query);
    // This count will be equal to the initial count
    Console.WriteLine("Updated Unread Count: " + messageInfoCol.Count());
}
else
{
    Console.WriteLine("No unread messages found");
}

การตั้งค่าการตรวจสอบ CRAM-MD5

สำหรับการตรวจสอบสิทธิ์ที่ปลอดภัยและการเข้าถึงเซิร์ฟเวอร์อีเมล Aspose.Email สำหรับ .NET มีวิธีการตรวจสอบ CRAM-MD5 ตัวอย่างโค้ดต่อไปนี้จะแสดงวิธีทำงานกับ ImapClient:

imapClient.AllowedAuthentication = ImapKnownAuthenticationType.CramMD5;

การตั้งค่าเวลาหมดสำหรับการดำเนินการ IMAP

การดำเนินการเมลแต่ละครั้งใช้เวลาตามปัจจัยหลายอย่าง (ความล่าช้าเครือข่าย, ขนาดข้อมูล, ประสิทธิภาพเซิร์ฟเวอร์ เป็นต้น) คุณสามารถตั้งค่าเวลาจำกัดสำหรับการดำเนินการเมลทั้งหมด ตัวอย่างโค้ดด้านล่างแสดงวิธีทำโดยใช้ เวลาจำกัด คุณสมบัติ หมายเหตุ: ไม่ควรกำหนดค่าขนาดใหญ่เพื่อหลีกเลี่ยงการรอคอยนานในแอปพลิเคชันของคุณ

กำหนดค่าเวลาหมดอายุของการดำเนินการ

using (ImapClient imapClient = new ImapClient("host", 993, "username", "password", SecurityOptions.SSLImplicit))
{
    imapClient.Timeout = 60000; // 60 seconds

    // some code...
}

จำกัดเวลา Greeting Timeout

ไคลเอนต์ IMAP อาจใช้โหมดอัตโนมัติในการสร้างการเชื่อมต่อ ในโหมดนี้ ไคลเอนต์ IMAP จะลองทุกพารามิเตอร์การเชื่อมต่อที่เป็นไปได้จนกว่าจะเชื่อมต่อสำเร็จ เซิร์ฟเวอร์ IMAP เมื่อการเชื่อมต่อถูกต้องจะส่งสตริงต้อนรับไปยังไคลเอนต์ เซิร์ฟเวอร์อาจเริ่มต้นการเชื่อมต่อ SSL/TLS แบบโดยอัตโนมัติหรือแบบชัดเจน (START TLS) หากโหมดการเชื่อมต่อไม่ตรงกัน (เช่น เซิร์ฟเวอร์รอการเชื่อมต่อ SSL แบบโดยอัตโนมัติแต่ไคลเอนต์พยายามเชื่อมต่อแบบไม่ปลอดภัยหรือแบบ SSL ชัดเจน) เซิร์ฟเวอร์จะไม่ส่งสตริงต้อนรับและผู้ใช้จะต้องรอเป็นเวลานานจนถึงการหมดเวลาเพื่อรับสตริงต้อนรับ และไคลเอนต์จะไปยังตัวเลือกการเชื่อมต่อถัดไป เพื่อหลีกเลี่ยงปัญหานี้ ได้มีการแนะนำคุณสมบัติ GreetingTimeout คุณสมบัตินี้ช่วยให้คุณตั้งค่าเวลาหมดสำหรับสตริงต้อนรับ และลดระยะเวลาในการสร้างการเชื่อมต่ออัตโนมัติ

using (ImapClient client = new ImapClient("localhost", 993, "username", "password"))
{
    client.GreetingTimeout = 4000;
    client.SelectFolder(ImapFolderInfo.InBox);
}

การใช้โปรโตคอลการเข้ารหัสกับ IMAP

Aspose.Email รองรับโปรโตคอลการเข้ารหัส SSL (ล่าช้า) และ TLS เพื่อให้ความปลอดภัยในการสื่อสาร. คุณสามารถเปิดการเข้ารหัสเชิงคริปโตเพื่อปกป้องการแลกเปลี่ยนข้อมูลระหว่างแอปพลิเคชันของคุณและเซิร์ฟเวอร์เมล.

หมายเหตุ: คุณควรตั้งค่าเฉพาะเวอร์ชันของโปรโตคอลที่รองรับโดย .NET Framework. หากเวอร์ชันบางส่วนของโปรโตคอลการเข้ารหัสไม่รองรับโดย .NET Framework ที่คุณใช้, จะถูกละเว้นและข้ามไป. ในกรณีนี้, จะไม่มีข้อยกเว้นถูกสร้าง. กรุณาใช้ SetSupportedEncryptionUnsafe เมธอดหากคุณต้องการตั้งค่าโปรโตคอลโดยไม่มีการตรวจสอบความเข้ากันได้.

ตัวอย่างโค้ดด้านล่างจะแสดงวิธีตั้งค่า TLS 1.3 สำหรับ ImapClient อินสแตนซ์ของคลาส.

using (ImapClient imapClient = new ImapClient("host", 993, "username", "password", SecurityOptions.SSLImplicit))
{
    imapClient.SupportedEncryption = EncryptionProtocols.Tls13;

    // some code...
}

ในกรณีที่โปรโตคอลการเข้ารหัสที่ระบุไม่รองรับในเวอร์ชันปัจจุบันของ .NET Framework, ความแตกต่างของพฤติกรรมระหว่าง SetSupportedEncryptionUnsafe เมธอดและ SupportedEncryption คุณสมบัติคือดังต่อไปนี้:

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

การใช้คำสั่ง IMAP IDLE

API ของ Aspose.Email ImapClient ให้ความสามารถในการเปิดการเชื่อมต่อไปยังเซิร์ฟเวอร์และรอการมาถึงของข้อความอีเมล ซึ่งช่วยหลีกเลี่ยงการสอบถามเซิร์ฟเวอร์ซ้ำ ๆ สำหรับอีเมลขาเข้า ตัวอย่างโค้ดต่อไปนี้แสดงวิธีใช้ไลบรารี Aspose.Email เพื่อตรวจสอบกล่องจดหมาย IMAP สำหรับข้อความใหม่และข้อความที่ถูกลบ แล้วทำการกระทำเฉพาะตามเหตุการณ์เหล่านั้น:

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect and log in to IMAP 
ImapClient client = new ImapClient("imap.domain.com", "username", "password");

ManualResetEvent manualResetEvent = new ManualResetEvent(false);
ImapMonitoringEventArgs eventArgs = null;
client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
{
    eventArgs = e;
    manualResetEvent.Set();
});
Thread.Sleep(2000);
SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
smtpClient.Send(new MailMessage("from@aspose.com", "to@aspose.com", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
manualResetEvent.WaitOne(10000);
manualResetEvent.Reset();
Console.WriteLine(eventArgs.NewMessages.Length);
Console.WriteLine(eventArgs.DeletedMessages.Length);
client.StopMonitoring("Inbox");
smtpClient.Send(new MailMessage("from@aspose.com", "to@aspose.com", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
manualResetEvent.WaitOne(5000);

ตัวอย่างโค้ดต่อไปนี้แสดงวิธีตั้งค่าการเฝ้าติดตาม แบบอะซิงโครนัส สำหรับข้อความอีเมลใหม่:

var client = = new ImapClient("imap.domain.com", "username", "password");

//anySuccess is a flag to prevent infinite Client.ResumeMonitoring calls
var anySuccess = false;
await client.StartMonitoringAsync(OnNewMessagesCallback, OnErrorCallback);

void OnErrorCallback(object eventSender, ImapMonitoringErrorEventArgs errorEventArguments)
{
    //The exception can be handled here
    Logger.Debug.Write(
        $"An error occured while folder monitoring: {errorEventArguments.FolderName}",
        errorEventArguments.Error);
    //IMAP folder monitoring is stopped on any error. Here is an example
    //of resuming after that.
    if (!anySuccess) return;
    anySuccess = false;
    //Make sure you use ResumeMonitoring instead of StartMonitoring here
    //to prevent missing any emails between the error handling and resuming.
    client.ResumeMonitoring(OnNewMessagesCallback, OnErrorCallback,
        errorEventArguments.MonitoringState);
}

void OnNewMessagesCallback(object sender, ImapMonitoringEventArgs successEventArgs)
{
    anySuccess = true;
    //Use successEventArgs.NewMessages to handle new messages
    //Use successEventArgs.DeletedMessages to handle deleted messages
}

รองรับส่วนขยายของ IMAP

Aspose.Email API ให้การสนับสนุนส่วนขยายของ IMAP ส่วนขยาย IMAP ต่อไปนี้ได้รับการสนับสนุนโดย API ในปัจจุบัน อย่างไรก็ตาม ส่วนขยายเหล่านี้ไม่ได้รับการสนับสนุนจากเซิร์ฟเวอร์ทั้งหมด

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (ImapClient client = new ImapClient("imap.gmail.com", 993, "username", "password"))
{
    // Set SecurityOptions
    client.SecurityOptions = SecurityOptions.Auto;
    Console.WriteLine(client.IdSupported.ToString());

    ImapIdentificationInfo serverIdentificationInfo1 = client.IntroduceClient();
    ImapIdentificationInfo serverIdentificationInfo2 = client.IntroduceClient(ImapIdentificationInfo.DefaultValue);

    // Display ImapIdentificationInfo properties
    Console.WriteLine(serverIdentificationInfo1.ToString(), serverIdentificationInfo2);
    Console.WriteLine(serverIdentificationInfo1.Name);
    Console.WriteLine(serverIdentificationInfo1.Vendor);
    Console.WriteLine(serverIdentificationInfo1.SupportUrl);
    Console.WriteLine(serverIdentificationInfo1.Version);
}

คำสั่งรายการขยาย IMAP4

โค้ดตัวอย่างต่อไปนี้แสดงวิธีการใช้คำสั่งรายการขยายของ IMAP4

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (ImapClient client = new ImapClient("imap.gmail.com", 993, "username", "password"))
{
    ImapFolderInfoCollection folderInfoCol = client.ListFolders("*");
    Console.WriteLine("Extended List Supported: " + client.ExtendedListSupported);
    foreach (ImapFolderInfo folderInfo in folderInfoCol)
    {
        switch (folderInfo.Name)
        {
            case "[Gmail]/All Mail":
                Console.WriteLine("Has Children: " + folderInfo.HasChildren);
                break;
            case "[Gmail]/Bin":
                Console.WriteLine("Bin has children? " + folderInfo.HasChildren);
                break;
            case "[Gmail]/Drafts":
                Console.WriteLine("Drafts has children? " + folderInfo.HasChildren);
                break;
            case "[Gmail]/Important":
                Console.WriteLine("Important has Children? " + folderInfo.HasChildren);
                break;
            case "[Gmail]/Sent Mail":
                Console.WriteLine("Sent Mail has Children? " + folderInfo.HasChildren);
                break;
            case "[Gmail]/Spam":
                Console.WriteLine("Spam has Children? " + folderInfo.HasChildren);
                break;
            case "[Gmail]/Starred":
                Console.WriteLine("Starred has Children? " + folderInfo.HasChildren);
                break;
        }
    }
}