Hadi Nemati
Hadi Nemati

Reputation: 547

Sending mass email in ASP.NET

This is my code to send lots of emails. I want to optimize this code to be sure that it will work and can successfully send all emails. What should I do? I know that putting interrupts between sending might be useful but how can I do this?

The main problem is avoiding classify emails as spam and decreasing number of failed sent emails.

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
}

Upvotes: 3

Views: 1650

Answers (2)

IrishChieftain
IrishChieftain

Reputation: 15253

With a little due diligence, this can be accomplished with a very simple console application which can be called from the Web form to dispatch the emails. By diligence, I mean to insert a pause between batches so that the mail server won't get bogged down. For example, if you were grabbing the addresses from a DB and sending them out, you could have something like:

if ((count >= 100) && (count % 100 == 0))
    Thread.Sleep(30000);
-----------------------------------------

// Web form code-behind

// Pass subject and message strings as params to console app

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);

Upvotes: 1

citronas
citronas

Reputation: 19365

I would advise you against adding all reciepients into the same mail message.

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);
}

Upvotes: 3

Related Questions