Fetched Emails not ordered when I use pop3 - c#

First I were Fetching emails by POP3 using this library OpenPop.Pop3 and it was working ok and it was returns emails ordered from last email to first email
but when I change the library to mailkit library the returned messages not ordered and couldn't know based on what mailkit order fetched emails
that's my code after I change to mailkit library
using (Pop3Client client = new Pop3Client())
{
// Connect to the server
client.Connect(hostname, port, useSsl);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate((username), password);
int messageCount = client.Count;
// We want to download all messages
List<MimeMessage> allMessages = new List<MimeMessage>(messageCount);
for (int i = messageCount-1; i > 0; i--)
{
var msg = client.GetMessage(i);
allMessages.Add(msg);
}
}
by this way allmessages variable should contains emails ordered from last email to first email but that's not happened emails not ordered at all
although I were using the same authenticated email before with OpenPop.Pop3 and fetched emails were ordered

I don't know why they wouldn't be ordered for you since MailKit is not doing any kind of sorting.
That said, MailKit uses 0-based indexes while I suppose OpenPOP.NET must have used 1-based indexes, so your loop should make the following change:
for (int i = messageCount-1; i >= 0; i--)
{
var msg = client.GetMessage(i);
allMessages.Add(msg);
}
Perhaps this will produce the expected results?
Update: It turns out that MailKit was correctly downloading the messages in reverse order just as his code was trying to do (as mentioned in his follow-up question). The problem this user was facing is that his GMail account settings were only providing MailKit's Pop3Client with a subset of his total Inbox as is explained in Google's FAQ in the section titled "Emails aren't downloading correctly", where it states:
After you set up POP in your Gmail settings, your emails become available
in batches. It might take a while to see all your emails.
Note: Gmail downloads a copy of every email you send or receive, except
for emails in Chats, Spam, and Trash. To avoid duplicates, Gmail doesn't
download emails sent within your mail client, but you can still see them
if you log in to Gmail.
If you continue to have problems downloading emails, try using recent
mode:
In your email client's POP settings page, find the "Email address" or
"User name" field.
Add recent: in front of your email address. For example,
recent:example#gmail.com.
If that doesn't fix the problem, try deleting your Gmail address from your email client, then re-adding it.

Related

DMARC failed for some Emails using SendGrid

I am writing a C# application that can send emails using the SendGridClient for .NET.
Everything is set up so far and kept working for a long time.
But since the last days, some emails are no longer forwarded to their target address. GMX and Outlook work, but Gmail does not work. Those addresses are listed as "Blocked" in the SendGrid Activity List because DMARC failed.
I'm sending the mail as following:
SendGridClient client = new SendGridClient(sendGridID);
EmailAddress from = new EmailAddress("xxx#mydomain.com", "My Sender");
EmailAddress to = new EmailAddress(customerEmail, customerName);
var subject = "Account has been created";
var textContent = "Your account has been successfully created";
var htmlContent = "Some Text";
var msg = MailHelper.CreateSingleEmail(from, to, subject, textContent, htmlContent);
await client.SendEmailAsync(msg);
I have checked DKIM and SPD, both seem to be okay. I do not really understand what the problem is. I read about misalignment of the email domains because I'm sending from mydomain.com but the mail itself comes then from sendgrid.net. Is this the problem? How do I fix this? I cannot send from sendgrid.net as this is not the source domain in my case. As I am not a SendGrid pro.. is there a way in SendGrid to configure this?
Blocks happen when your message was rejected for a reason related to the message, not the recipient address. This can happen when your mail server IP address has been added to a deny list, blocked by an ISP, or if the message content is flagged by a filter on the receiving server.
The “Reason on the Block” will clarify what the exact reason is. Typically, it’s possible to have your IP address removed from a deny list, and some lists automatically do this after a period of time. Message content can be modified to correct a filtered block.
Moreover, you can use Address Whitelisting to whitelist Gmail domain. The address whitelist setting whitelists a specified email address or domain for which mail should never be suppressed. For example, you own the domain example.com, and one or more of your recipients use email#example.com addresses, by placing example.com in the address whitelist setting, all bounces, blocks, and unsubscribes logged for that domain will be ignored and sent as if under normal sending conditions.
Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's Web API or SMTP Relay.
C# code:
string data = #"{
'enabled': true,
'list': [
'email1#example.com',
'example.com'
]
}";
var json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/address_whitelist", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();

How to mark message as read, properly get from address and delete message

It seems as though I can finally access the service and get all unread mails from the inbox by using the EWS API but it seems as though the message doesn't send
EmailMessage message = new EmailMessage(emailService);
message.Subject = string.Format("Electricity token for: {0}", house.Number);
message.Body = html.HTMLCode;
message.ToRecipients.Add(email.From);
message.SendAndSaveCopy();
"email" refers to the list of unread emails I get back
what must I do to correctly get the senders email address and how do I mark it as read and then delete it?
Based on your other post, it appears that the problem was indeed that you hadn't bound to the original mail.

MailKit Delete single message from gmail

I am using MailKit (https://github.com/jstedfast/MailKit) to connect to google apps via imap, how can I delete a single message though ? (I am fine to have it moved to trash, just need it out of the inbox.
So far I have it connected, downloading, parsing links from message bodies. I just need this one last action to have what I need.
Thanks!
To delete a message from a folder on the IMAP server, this is all you need to do:
client.Inbox.AddFlags (new int[] { index }, MessageFlags.Deleted);
or
client.Inbox.AddFlags (new UniqueId[] { uid }, MessageFlags.Deleted);
Now the message is marked as \Deleted on the server.
You can then purge the folder of all deleted items by calling:
client.Inbox.Expunge ();
If you are using UIDs instead of indexes and the IMAP server supports the UIDPLUS extension (check the client.Capabilities), you can expunge just a selected set of messages like this:
if (client.Capabilities.HasFlag (ImapCapabilities.UidPlus))
client.Inbox.Expunge (new UniqueId[] { uid });

how to send email in C# even when one of the recipient is invalid?

I am trying to send email to multiple recipients and it works fine when all the recipients have valid email address.
But when one of the recipients have invalid email address, email is not sent even to other recipients whose email address is valid and I am getting an exception:
The server rejected one or more recipient addresses. The server
response was: 550 #5.1.0 Address rejected.
Is there any way I can send the email to other valid recipients even if one of the email address is invalid?
public static void sendMails(string ptxtSubject, string ptxtBody)
{
string txtTo = "valid1#aaa.com,valid2#aaa.com,invalid1#aaa.com";
string txtFrom = "valid#aaa.com";
string txtSubject = ptxtSubject;
string txtBody = ptxtBody;
MailMessage mail = new MailMessage();
mail.To = txtTo;
mail.From = txtFrom;
mail.Subject = txtSubject;
mail.Body = txtBody;
try
{
SmtpMail.SmtpServer ="smtp.aaa.com";
SmtpMail.Send(mail);
}
catch (Exception ex)
{
//log the exception
throw;
}
}
I can send separate mail to each of them but users(recipients) will not know who else is in the email distribution list. My requirement is everyone should be able to know who else is receiving the email.
Outlook sends the email to all the valid users and notifies us back of invalid users. Is there anyway we can do the same using C#?
Unless all the recipients definitely know each other (and they don't mind other people knowing they are receiving email from you), you should be sending separate emails anyway.
This would also take care of your problem, i.e. if one send operation fails, it won't disrupt the others. Note that in your case, it appears that the initial relay is failing because the addresses are from the same host as the SMTP server.
Once an email is routed to multiple hosts, the success/failure is no longer interdependent. For example, a gmail.com server probably doesn't know/care that a yahoo.com server rejected a recipient.
If performance is a concern, you can send the messages asynchronously to get achieve better throughput. Note that you can still handle exceptions when sending asynchronously.
As always, if you are sending any quantity of email, it's probably advisable to use a 3rd party service.
I really don't see any way to accomplish this. Sending an email with SmtpMail.Send() is pretty much an atomic function and you need correct data for it to work without an exception.
The only option I see here is to send separate emails to each recipient.

OpenPop - Gmail - GetMessageCount() returns 0 (zero)

When connecting to Gmail with OpenPop, I can only retrieve an email once, even if I do not delete it. Using GetMessageCount() I always receive 0 emails. How can I get all the emails that are there?
Only after reading them and processing them do I give order to delete. I am using the following code to get the emails:
using (var client = new Pop3Client())
{
// Connect to the server
client.Connect(serverData.Hostname, serverData.Port, serverData.UseSsl);
// Authenticate ourselves towards the server
client.Authenticate(serverData.Username, serverData.Password, AuthenticationMethod.UsernameAndPassword);
var emailAmount = client.GetMessageSizes().Count;
// Fetch all the current uids seen
var msgCount = client.GetMessageCount();
.....
}
Gmail is special. Take a look at this StackOverflow post which explains the non-standard behavior.
What you are interested in, is that Gmail will only show a message in ONE POP3 session, unless you do special stuff, like prepending recent: in front of your username.
Getting only the unread mails is how POP3 is supposed to work. If you want to see and manage older mails, you should use IMAP instead.

Categories