Cách Thiết Lập Kết Nối IMAP trong C#
Liệt Kê Các Phần Mở Rộng Máy Chủ IMAP
Aspose.Email ImapClient cho phép bạn truy xuất các phần mở rộng mà máy chủ hỗ trợ như IDLE, UNSELECT, QUOTA, v.v. Điều này giúp xác định tính khả dụng của một phần mở rộng trước khi sử dụng client cho chức năng đó. The GetCapabilities() phương thức trả về các loại phần mở rộng được hỗ trợ dưới dạng mảng chuỗi. Đoạn mã sau đây cho bạn thấy cách truy xuất các phần mở rộng.
Kết Nối IMAP Tiêu Chuẩn
Cái ImapClient lớp cho phép các ứng dụng quản lý hộp thư IMAP bằng giao thức IMAP. ImapClient lớp được sử dụng để kết nối tới máy chủ thư IMAP và quản lý email trong các thư mục email IMAP. Để kết nối tới máy chủ IMAP
- Tạo một đối tượng của ImapClient lớp.
- Xác định tên máy, tên người dùng và mật khẩu trong ImapClient constructor.
Lưu ý, các hạn chế về mật khẩu phải đáp ứng yêu cầu của máy chủ. Ứng dụng khách email không thêm các hạn chế mật khẩu.
Khi ImapClient phiên bản được khởi tạo, lần gọi tiếp theo tới bất kỳ thao tác nào sử dụng phiên bản này sẽ kết nối tới máy chủ. Đoạn mã sau cho bạn thấy cách kết nối tới máy chủ IMAP bằng các bước trên.
// 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");
Kết Nối IMAP Có SSL
Kết nối với máy chủ IMAP mô tả cách kết nối tới máy chủ IMAP trong bốn bước đơn giản:
- Tạo một đối tượng của ImapClient lớp.
- Xác định tên máy, tên người dùng và mật khẩu.
- Xác định cổng.
- Chỉ định các tùy chọn bảo mật.
Quá trình kết nối tới máy chủ IMAP hỗ trợ SSL tương tự nhưng yêu cầu bạn đặt một vài thuộc tính khác:
- Thiết lập SecurityOptions đến SSLImplicit.
Đoạn mã sau cho thấy cách
- Đặt tên người dùng, mật khẩu và cổng.
- Đặt tùy chọn bảo mật.
// 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;
Cấu Hình Kết Nối Proxy
Kết nối tới Máy chủ qua Proxy
Các máy chủ proxy thường được dùng để giao tiếp với bên ngoài. Trong các trường hợp như vậy, các khách hàng email không thể giao tiếp qua Internet nếu không chỉ định địa chỉ proxy. Aspose.Email hỗ trợ các phiên bản 4, 4a và 5 của giao thức proxy SOCKS. Bài viết này cung cấp một mẫu thực tế về cách truy cập hộp thư bằng máy chủ proxy. Để truy cập hộp thư qua máy chủ proxy:
- Khởi tạo SocksProxy với thông tin cần thiết, bao gồm địa chỉ proxy, cổng và phiên bản SOCKS.
- Khởi tạo ImapClient với địa chỉ host, tên người dùng, mật khẩu và bất kỳ cài đặt nào khác.
- Đặt SocksProxy thuộc tính của client thành SocksProxy đối tượng được tạo ở trên.
Đoạn mã sau cho bạn thấy cách truy xuất hộp thư qua máy chủ proxy.
// 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);
}
Kết nối tới máy chủ qua 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");
}
Kết Nối Chế Độ Chỉ Đọc
Cái ImapClient lớp cung cấp một ReadOnly thuộc tính khi được đặt thành true, chỉ ra rằng không nên thay đổi trạng thái cố định của hộp thư. Mẫu mã sau minh họa việc sử dụng ImapClient.ReadOnly thuộc tính. Nó lấy số lượng tin nhắn chưa đọc, sau đó lấy một tin nhắn và lại lấy số lượng tin nhắn chưa đọc trong chế độ chỉ đọc. Số lượng tin nhắn chưa đọc vẫn giữ nguyên cho thấy trạng thái cố định của hộp thư không bị thay đổi.
// 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");
}
Cài Đặt Xác Thực CRAM-MD5
Để xác thực an toàn và truy cập máy chủ email, Aspose.Email cho .NET cung cấp phương pháp xác thực CRAM-MD5. Đoạn mã sau sẽ cho bạn thấy cách nó hoạt động với ImapClient:
imapClient.AllowedAuthentication = ImapKnownAuthenticationType.CramMD5;
Đặt Thời Gian Chờ cho Các Thao Tác IMAP
Mỗi thao tác mail mất một khoảng thời gian tùy thuộc vào nhiều yếu tố (độ trễ mạng, kích thước dữ liệu, hiệu suất máy chủ, v.v.). Bạn có thể đặt thời gian chờ cho tất cả các thao tác mail. Ví dụ mã dưới đây cho bạn thấy cách thực hiện điều đó bằng cách sử dụng Thời gian chờ thuộc tính. Lưu ý: bạn không nên đặt giá trị quá lớn để tránh thời gian chờ lâu trong ứng dụng của bạn.
Cấu Hình Thời Gian Chờ Thao Tác
using (ImapClient imapClient = new ImapClient("host", 993, "username", "password", SecurityOptions.SSLImplicit))
{
imapClient.Timeout = 60000; // 60 seconds
// some code...
}
Hạn Chế Thời Gian Chờ Lời Chào
Client IMAP có thể sử dụng chế độ tự động để thiết lập kết nối. Trong chế độ này, client IMAP sẽ thử tất cả các tham số kết nối khả dụng cho đến khi kết nối thành công. Máy chủ IMAP trong trường hợp kết nối đúng sẽ gửi một chuỗi chào tới client. Các máy chủ có thể sử dụng khởi tạo kết nối SSL/TLS ngầm định hoặc rõ ràng (START TLS). Nếu chế độ kết nối không khớp (ví dụ, máy chủ chờ kết nối SSL ngầm định nhưng client cố gắng thiết lập kết nối không bảo mật hoặc SSL rõ ràng), máy chủ sẽ không gửi chuỗi chào và người dùng sẽ phải chờ lâu cho tới khi hết thời gian chờ, và client sẽ chuyển sang tùy chọn kết nối tiếp theo. Để tránh vấn đề này, thuộc tính GreetingTimeout đã được giới thiệu. Thuộc tính này cho phép bạn đặt thời gian chờ cho chuỗi chào, và giảm thời gian thiết lập kết nối tự động.
using (ImapClient client = new ImapClient("localhost", 993, "username", "password"))
{
client.GreetingTimeout = 4000;
client.SelectFolder(ImapFolderInfo.InBox);
}
Sử Dụng Giao Thức Mã Hoá với IMAP
Aspose.Email hỗ trợ các giao thức mã hóa SSL (cũ) và TLS để cung cấp bảo mật giao tiếp. Bạn có thể bật mã hóa mật mã để bảo vệ việc trao đổi dữ liệu giữa ứng dụng của mình và máy chủ mail.
LƯU Ý: Bạn chỉ nên đặt các phiên bản giao thức mà .NET Framework hỗ trợ. Nếu một số phiên bản của giao thức mã hóa không được phiên bản .NET Framework hiện tại của bạn hỗ trợ, chúng sẽ bị bỏ qua và không gây ra ngoại lệ. Vui lòng sử dụng SetSupportedEncryptionUnsafe phương thức nếu bạn muốn đặt các giao thức mà không có kiểm tra tương thích nào.
Ví dụ mã dưới đây cho bạn cách thiết lập TLS 1.3 cho ImapClient đối tượng lớp.
using (ImapClient imapClient = new ImapClient("host", 993, "username", "password", SecurityOptions.SSLImplicit))
{
imapClient.SupportedEncryption = EncryptionProtocols.Tls13;
// some code...
}
Trong trường hợp giao thức mã hóa được chỉ định không được hỗ trợ trong phiên bản hiện tại của .NET Framework, sự khác biệt trong hành vi giữa SetSupportedEncryptionUnsafe phương thức và SupportedEncryption thuộc tính như sau:
- Nếu SupportedEncryption thuộc tính này được sử dụng, trình khách email hạ cấp giao thức mã hóa xuống mức hỗ trợ.
- Nếu SetSupportedEncryptionUnsafe phương thức này được sử dụng, trình khách email sẽ ném ra ngoại lệ.
Sử Dụng Lệnh IMAP IDLE
API của Aspose.Email ImapClient cung cấp khả năng mở kết nối tới máy chủ và chờ đợi sự xuất hiện của một tin nhắn email. Điều này cho phép tránh việc liên tục truy vấn máy chủ để kiểm tra email mới. Đoạn mã sau minh họa cách sử dụng thư viện Aspose.Email để giám sát hộp thư đến IMAP cho các tin nhắn mới và tin nhắn đã bị xóa, sau đó thực hiện các hành động cụ thể dựa trên các sự kiện này:
// 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);
Mẫu mã sau cho thấy cách thiết lập giám sát bất đồng bộ cho các tin nhắn email mới:
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
}
Hỗ trợ các Tiện ích mở rộng IMAP
API Aspose.Email cung cấp hỗ trợ cho các tiện ích mở rộng IMAP. Các tiện ích mở rộng IMAP sau hiện đang được API hỗ trợ. Những tiện ích mở rộng này không được tất cả máy chủ hỗ trợ.
// 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);
}
Lệnh Danh sách Mở rộng IMAP4
Đoạn mã dưới đây cho bạn thấy cách sử dụng lệnh danh sách mở rộng 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;
}
}
}