Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sending SMTP using System.Threading

I have developed an application which primarily sends email messages uses SMTP. Sending messages one by one is fine, however I am looking to speed the process. I have created multiple instances of the SmtpClient as well as messages to avoid conflict among each other. Because of the separate instances, I assumed performing .Send() on multiple threads would work well. However, something with my Thread code alone is not working, because I can not send even one email on one thread using this code. I simply receive a vague "Failure sending mail" exception. I will post code that works, and the Thread that does not work. Could someone share what they believe may be the cause?

Note I am not currently looking to use the newer async capabilities but instead leveraging Thread

Working Declaration and Method Call:

var SMTP = new SmtpClient
    {
        Host = txtBxSenderHost.Text,
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(strSenderAddress, strSenderPassword)
    };

using (var message = new MailMessage(senderAdrress, toAddress)
    {
        Subject = strSubject,
        Body = strBody
    })

    {
        SMTP.Send(message);
    }

NOT Working Thread declaration and Method Call:

var SMTP = new SmtpClient
    {
        Host = txtBxSenderHost.Text,
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(strSenderAddress, strSenderPassword)
    };

using (var message = new MailMessage(senderAdrress, toAddress)
    {
        Subject = strSubject,
        Body = strBody
    })

    {
        Thread T1 = new Thread(delegate() { SMTP.Send(message); } );
        T1.Start();
    }
like image 663
scniro Avatar asked Jan 25 '13 09:01

scniro


1 Answers

Solved:

var SMTP = new SmtpClient
        {
            Host = txtBxSenderHost.Text,
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(strSenderAddress, strSenderPassword)
        };

        Thread T1 = new Thread(delegate()
        {
            using (var message = new MailMessage(senderAdrress, toAddress)
            {
                Subject = strSubject,
                Body = strBody
            })
            {
                {
                    SMTP.Send(message);
                }
            }
        });

        T1.Start();
like image 75
nsconnector Avatar answered Oct 17 '22 00:10

nsconnector