我正在使用MailKit接收电子邮件。
这是我的代码:
using (var emailClient = new Pop3Client())
{
emailClient.Connect(settings.HostMail, 110);
emailClient.Authenticate(settings.UsernameEmail, settings.PasswordEmail);
List<EmailMessageDTO> emails = new List<EmailMessageDTO>();
for (int i = 0; i < emailClient.Count; i++)
{
var message = emailClient.GetMessage(i);
var emailMessage = new EmailMessageDTO();
emailMessage.MessageHtml = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody;
emailMessage.Subject = message.Subject;
emailMessage.To = new List<DTO.Address>();
emailMessage.To.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new DTO.Address { Email = x.Address, Name = x.Name }));
var sender = message.From.Select(x => (MailboxAddress)x).Select(x => new DTO.Address { Email = x.Address, Name = x.Name }).FirstOrDefault();
emailMessage.From = new DTO.Address { Email = sender.Email, Name = sender.Name };
if(emailMessage.From.Name == "Ali")
{
emails.Add(emailMessage);
}
}
}
问题是,上面的代码会循环获取所有电子邮件,然后搜索从特殊帐户收到的电子邮件。有没有办法列出从帐户收到的电子邮件,而不在for
循环中获取所有电子邮件?
POP3协议非常基本,不支持任何搜索方式。IMAP协议将是一个更好的协议,可以满足您的需求,但如果您没有这个选项,您可以(潜在地(通过只下载邮件头来进行过滤,然后下载完整的邮件来提高应用程序的网络性能。
例如:
for (int i = 0; i < emailClient.Count; i++)
{
var headers = emailClient.GetMessageHeaders(i);
if (!headers.TryGetValue (HeaderId.From, out var header))
continue;
if (!InternetAddressList.TryParse (header.RawValue, out var addrList))
continue;
var sender = addrList.Mailboxes.FirstOrDefault ();
if (sender == null || sender.Name != "Ali")
continue;
var message = emailClient.GetMessage(i);
var emailMessage = new EmailMessageDTO();
emailMessage.MessageHtml = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody;
emailMessage.Subject = message.Subject;
emailMessage.To = new List<DTO.Address>();
emailMessage.To.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new DTO.Address { Email = x.Address, Name = x.Name }));
emailMessage.From = new DTO.Address { Email = sender.Address, Name = sender.Name };
emails.Add(emailMessage);
}