I am using MailKit to receive emails.
Here is my code:
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);
}
}
}
The problem is that the above code gets all emails in a loop and then searches for the email messages received from an special account. Is there any way to list the email messages received from the account without getting all email messages in the for loop?
CodePudding user response:
The POP3 protocol is very basic and does not support any way of searching. The IMAP protocol would be a better protocol for what you want to do, but if you don't have that option, you could (potentially) improve network performance of your app by downloading only the headers in order to do your filtering and then, if it matches, download the full message.
For example:
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);
}
