Sending bulk emails in c # .net windows application - c#

My project is to send at least 100 mails an hour.
I have used for loop to retrieve emails from database and send email one by one.
But When I googled i find out that it will get time out after some time.So What is the method to use to hold the mail sending for a while and then restart the loop from hold position.Also,if the sending failed i should resend it.Should I use timer?
Please provide me any idea to complete this.
My sample code,
List<string> list = new List<string>();
String dbValues;
foreach (DataRow row in globalClass1.dtgrid.Rows)
{
//String From DataBase(dbValues)
dbValues = row["email"].ToString();
list.Add(dbValues);
}
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(mailserver, port))
{
client.Credentials = new System.Net.NetworkCredential(emailfrom, password);
client.EnableSsl = true;
MailMessage msg1 = new MailMessage();
foreach (string row in list)
{
if (row != null)
{
msg1=sendmail(row);
client.Send(msg1);
client.Dispose();
}
}}

Option 1
You can simply Add multiple recipients to To property of MailMessage:
var mail = new MailMessage();
mail.To.Add(new MailAddress("to#example.com"));
For example when you have a list that contains recipients, you can add theme all:
var mail = new MailMessage();
foreach (var item in list)
{
mail.To.Add(new MailAddress(item));
}
mail.From = new MailAddress("from#example.com");
mail.Subject = "Subject";
mail.Body = "Body";
client.Send(mail);
Option 2
If you don't want to set all addresses using To or Bcc you can can use a Task to send emails this way:
public void SendMails(List<string> list)
{
Task.Run(() =>
{
foreach (var item in list)
{
//Put all send mail codes here
//...
//mail.To.Add(new MailAddress(item));
//client.Send(mail);
}
});
}
Option 3
You can also use SendMailAsync to send mails.
Thanks to Panagiotis Kanavos to mention that this way is preferred instead of using Task.Run .

You should rather send them asynchronously using the pickup directory. Here is a good overview. http://weblogs.asp.net/gunnarpeipman/asp-net-using-pickup-directory-for-outgoing-e-mails
The SMTP server handles transient network connectivity issues, and retries periodically.

Related

Retrieve unread emails and leave them as unread in inbox

I'm using GemBox.Email and I'm retrieving unread emails from my inbox like this:
using (var imap = new ImapClient("imap.gmail.com"))
{
imap.Connect();
imap.Authenticate("username", "password");
imap.SelectInbox();
IEnumerable<string> unreadUids = imap.ListMessages()
.Where(info => !info.Flags.Contains(ImapMessageFlags.Seen))
.Select(info => info.Uid);
foreach (string uid in unreadUids)
{
MailMessage unreadEmail = imap.GetMessage(uid);
unreadEmail.Save(uid + ".eml");
}
}
The code is from the Receive example, but the problem is that after retrieving them they end up being marked as read in my inbox.
How can I prevent this from happening?
I want to download them with ImapClient and leave them as unread on email server.
EDIT (2021-01-19):
Please try again with the latest version from the BugFixes page or from NuGet.
The latest version provides ImapClient.PeekMessage methods which you can use like this:
using (var imap = new ImapClient("imap.gmail.com"))
{
imap.Connect();
imap.Authenticate("username", "password");
imap.SelectInbox();
foreach (string uid in imap.SearchMessageUids("UNSEEN"))
{
MailMessage unreadEmail = imap.PeekMessage(uid);
unreadEmail.Save(uid + ".eml");
}
}
ORIGINAL:
When retrieving an email, most servers will mark it with the "SEEN" flag. If you want to leave an email as unread then you can just remove the flag.
Also, instead of using ImapClient.ListMessages you could use ImapClient.SearchMessageUids to get IDs of unread emails.
So, try the following:
using (var imap = new ImapClient("imap.gmail.com"))
{
imap.Connect();
imap.Authenticate("username", "password");
imap.SelectInbox();
// Get IDs of unread emails.
IEnumerable<string> unreadUids = imap.SearchMessageUids("UNSEEN");
foreach (string uid in unreadUids)
{
MailMessage unreadEmail = imap.GetMessage(uid);
unreadEmail.Save(uid + ".eml");
// Remove "SEEN" flag from read email.
imap.RemoveMessageFlags(uid, ImapMessageFlags.Seen);
}
}

EWS - Determine if an e-mail is a reply or has been forwarded

I am using the Exchange Web Services Managed API 2.2 to monitor users inboxes and need to determine if an e-mail is a new item, a reply or a forwarded message.
I have seen various articles on SO such as how to notice if a mail is a forwarded mail? and Is there a way to determine if a email is a reply/response using ews c#? which both help in their specific cases but I still cannot work out how to distinguish between a reply and a forwarded item.
In the first article an extra 5 bytes is added each time (forward or reply) so I don't know what the last action was.
The second article suggests using the InReplyTo however when I examine the property for forwarded e-mails it contains the original senders e-mail address (not null).
I have seen other articles such as this or this that suggest using extended properties to examine the values in PR_ICON_INDEX, PR_LAST_VERB_EXECUTED and PR_LAST_VERB_EXECUTION_TIME.
My code looks as follows but never returns a value for lastVerbExecuted
var lastVerbExecutedProperty = new ExtendedPropertyDefinition(4225, MapiPropertyType.Integer);
var response = service.BindToItems(newMails, new PropertySet(BasePropertySet.IdOnly, lastVerbExecutedProperty));
var items = response.Select(itemResponse => itemResponse.Item);
foreach (var item in items)
{
object lastVerb;
if (item.TryGetProperty(lastVerbExecutedProperty, out lastVerb))
{
// do something
}
}
PR_ICON_INDEX, PR_LAST_VERB_EXECUTED and PR_LAST_VERB_EXECUTION_TIME would only work to tell you if the recipient has acted on a message in their Inbox. Eg if the user had replied or forwarded a message in their inbox then these properties get set on the message in their Inbox. On the message that was responded to or forwarded these properties would not be set. I would suggest you use the In-Reply-To Transport header which should be set on any message that is replied to or forwarded, this should contain the internet messageid of the message that was replied to or forwarded eg.
FindItemsResults<Item> fiRs = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
PropertySet fiRsPropSet = new PropertySet(BasePropertySet.FirstClassProperties);
ExtendedPropertyDefinition PR_TRANSPORT_MESSAGE_HEADERS = new ExtendedPropertyDefinition(0x007D, MapiPropertyType.String);
fiRsPropSet.Add(PR_TRANSPORT_MESSAGE_HEADERS);
service.LoadPropertiesForItems(fiRs.Items, fiRsPropSet);
foreach (Item itItem in fiRs)
{
Object TransportHeaderValue = null;
if(itItem.TryGetProperty(PR_TRANSPORT_MESSAGE_HEADERS,out TransportHeaderValue)) {
string[] stringSeparators = new string[] { "\r\n" };
String[] taArray = TransportHeaderValue.ToString().Split(stringSeparators, StringSplitOptions.None);
for (Int32 txCount = 0; txCount < taArray.Length; txCount++)
{
if (taArray[txCount].Length > 12)
{
if (taArray[txCount].Substring(0, 12).ToLower() == "in-reply-to:")
{
String OriginalId = taArray[txCount].Substring(13);
Console.WriteLine(OriginalId);
}
}
}
}
}
Apart from the Subject prefix that was discussed in the other link I don't know of any other proprieties that will differentiate between a reply or forward.
Cheers
Glen
The best way to rely is on the ResponeCode of Extended properties
Refer below scripts
private static int IsForwardOrReplyMail(ExchangeService service, EmailMessage messageToCheck)
{
try
{
// Create extended property definitions for PidTagLastVerbExecuted and PidTagLastVerbExecutionTime.
ExtendedPropertyDefinition PidTagLastVerbExecuted = new ExtendedPropertyDefinition(0x1081, MapiPropertyType.Integer);
ExtendedPropertyDefinition PidTagLastVerbExecutionTime = new ExtendedPropertyDefinition(0x1082, MapiPropertyType.SystemTime);
PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, PidTagLastVerbExecutionTime, PidTagLastVerbExecuted);
messageToCheck = EmailMessage.Bind(service, messageToCheck.Id, propSet);
// Determine the last verb executed on the message and display output.
object responseType;
messageToCheck.TryGetProperty(PidTagLastVerbExecuted, out responseType);
if (responseType != null && ((Int32)responseType) == 104)
{
//FORWARD
return 104;
}
else if (responseType != null && ((Int32)responseType) == 102)
{
//REPLY
return 102;
}
}
catch (Exception)
{
return 0;
//throw new NotImplementedException();
}
}
To determine if it was a reply to a email, you can use the EmailMessage objects InReplyTo property, e.g:
EmailMessage mail = ((EmailMessage)Item.Bind(service, new ItemId(UniqueId)));
if (mail.InReplyTo == null)
return;
else
..your code

System.Net.Mail.MailMessage/System.Net.Mail.SmtpClient Sending Duplicate Emails

The code below uses System.Net.Mail.MailMessage/System.Net.Mail.SmtpClient to email files from a ASP.NET/C# 3.5SP1 application running on IIS7 on Windows 2008R2. Even though we haven't changed the code in 3+ years, it has recently started sending duplicate emails. For example, if me#me.com is the currentVendor.Email, me#me.com receives 2 separate emails exactly the same. Any ideas? Would a Windows Update have caused this?
Vendor currentVendor = Vendor.GetCurrent();
string POLocation = Vendor.GetPOLocation();
#if !DEBUG
MailMessage mailer = new MailMessage("orders#perks.com", "resdev#perks.com");
string[] addresses = currentVendor.Email.Split(new char[] { ';', ',' });
foreach (string recip in addresses)
{
mailer.To.Add(recip.Trim());
}
#else
MailMessage mailer = new MailMessage("orderstest#me.com", "devtest#me.com");
#endif
mailer.Subject = String.Format("{0} V2 Purchase Orders - {1}", currentVendor.Name, DateTime.Today.ToShortDateString());
mailer.IsBodyHtml = true;
mailer.Body = "Please find attached..... <br/>" +
"This email is system generated. If you have any trouble please, contact us";
mailer.Attachments.Add(new Attachment(POLocation));
SmtpClient mailClient = new SmtpClient();
mailClient.Send(mailer);
Thanks in advance!
Try to check if this code:
Vendor currentVendor = Vendor.GetCurrent();
does not return duplicated email addresses?
There is only one call to MailClient.Send() method:
mailClient.Send(mailer);
But make sure you don't call the entire code snippet which you have pasted more than once!

How can I know if my sent email was successful [duplicate]

This question already has answers here:
How to check if the mail has been sent successfully
(8 answers)
Closed 8 years ago.
I am trying to develop an application which sends email to multiple recepients.
I am reading all the mail addresses from a text file line by line.But I am wondering ..for example I have 50 mail addresses in my list and something went wrong with the number 45.
How can I inform the user about about it and is it possibble sending the rest of the list?
private void Senmail(IEnumerable<string> list)
{
var mes = new MailMessage {From = new MailAddress(_uname.Trim())};
var col = new MailAddressCollection();
foreach (string adres in list)
{
col.Add(adres);
}
for (int i = 0; i < GetList().Count(); i++)
{
mes.To.Add(col[i].Address);
}
mes.Subject = txtbody.Text;
mes.Body = txtmail.Text;
mes.Attachments.Add(new Attachment(_filename));
var client = new SmtpClient
{
Port = 587,
Host = "smtp.gmail.com",
EnableSsl = true,
Timeout = 5000,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(_uname, _pass),
};
object userState = mes;
client.SendAsync(mes,userState);
client.SendCompleted += client_SendCompleted;
MessageBox.Show("ok");
}
void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error!=null)
{
//
}
}
Since you're using Gmail your options are very limited. At best you will get an exception if the SMTP host cannot be reached, but if you get a 200 response then you have technically fulfilled the end of your delivery contract and any subsequent response will be delivered after the fact (email does not exist, for example).
You might find some extra options under MailMessage's DeliveryNotificationOptions property and handle exceptions, but these are limited and really don't provide what I believe you are looking for.

Read email one at a time using IMap4Client

I'm reading emails using Imap. My code, which is working, is as follows:
Client.ConnectSsl(mailServer, port);
Mailbox mails = Client.SelectMailbox("inbox");
MessageCollection messages = mails.SearchParse("UNSEEN");
return messages;
But I want to get one email at a time instead of getting all the messages as a MessageCollection. I don't want to loop through MessageCollection either. Is there any method which returns only one message?
For example :
Message email = mails.Search("UNSEEN");
Thank you.
You can Find the below solution
Imap4Client imap = new Imap4Client();
imap.ConnectSsl("imap.gmail.com", 993);
imap.Login("abc#gmail.com", "thatsmypassword");
imap.Command("capability");
Mailbox inbox = imap.SelectMailbox("inbox");
int[] ids = inbox.Search("UNSEEN");
if (ids.Length > 0)
{
Message msg_first = inbox.Fetch.MessageObject(ids[0]);
}
Thanks,
Gauttam

Categories