Sending Bulk Email in ASP.NET
This is my code for sending a lot of emails. I want to optimize this code to make sure it will work and can send all emails successfully. What should I do? I know that transferring interrupts between dispatches can be helpful, but how can I do that?
The main problem is not to classify emails as spam and to reduce the number of deleted messages sent.
var list = from c in context.Emails orderby c.EmailAddress select c.EmailAddress;
MailMessage mail = new MailMessage();
try
{
mail.From = new MailAddress(txtfrom.Text);
foreach (var c in list)
{
mail.To.Add(new MailAddress(c.ToString()));
}
mail.Subject = txtSub.Text;
mail.IsBodyHtml = true;
mail.Body = txtBody.Text;
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(
FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
catch (Exception)
{
//exception handling
}
source to share
I would advise you not to add all registries to the same mailing.
Rather use this code:
mail.From = new MailAddress(txtfrom.Text);
mail.Subject = txtSub.Text;
mail.IsBodyHtml = true;
mail.Body = txtBody.Text;
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
foreach (var c in list)
{
mail.To.Clear();
mail.To.Add(new MailAddress(c.ToString()));
smtp.Send(mail);
}
source to share
With a little due diligence, this can be accomplished with a very simple console application that can be called from a web form to send emails. With diligence, I want to insert a pause between batches so that the mail server doesn't get bogged down. For example, if you grab addresses from the DB and send them, you might have something like:
if ((count >= 100) && (count % 100 == 0))
Thread.Sleep(30000);
-----------------------------------------
// Web form code
// Pass subject and message strings as parameters for the console application
ProcessStartInfo info = new ProcessStartInfo();
string arguments = String.Format(@"""{0}"" ""{1}""",
subjectText.Text.Replace(@"""", @""""""),
messageText.Text.Replace(@"""", @""""""));
info.FileName = MAILER_FILEPATH;
Process process = Process.Start(info.FileName, arguments);
Process.Start(info);
More info here: Calling a Console Application from a Web Form
source to share