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();
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With