I\'m developing an application where a user clicks/presses enter on a certain button in a window, the application does some checks and determines whether to send out a coupl
Use the SmtpClient class and use the method SendAsync in the System.Net.Mail namespace.
It's not too complicated to simply send the message on a separate thread:
using System.Net.Mail;
Smtp.SendAsync(message);
Or if you want to construct the whole message on the separate thread instead of just sending it asynchronously:
using System.Threading;
using System.Net.Mail;
var sendMailThread = new Thread(() => {
var message=new MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
SmtpMail.SmtpServer="SMTP Server Address";
SmtpMail.Send(message);
});
sendMailThread.Start();
As it's a small unit of work you should use ThreadPool.QueueUserWorkItem for the threading aspect of it. If you use the SmtpClient class to send your mail you could handle the SendCompleted event to give feedback to the user.
ThreadPool.QueueUserWorkItem(t =>
{
SmtpClient client = new SmtpClient("MyMailServer");
MailAddress from = new MailAddress("me@mydomain.com", "My Name", System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("someone@theirdomain.com");
MailMessage message = new MailMessage(from, to);
message.Body = "The message I want to send.";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "The subject of the email";
message.SubjectEncoding = System.Text.Encoding.UTF8;
// Set the method that is called back when the send operation ends.
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, I am passing the message itself
client.SendAsync(message, message);
});
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the message we sent
MailMessage msg = (MailMessage)e.UserState;
if (e.Cancelled)
{
// prompt user with "send cancelled" message
}
if (e.Error != null)
{
// prompt user with error message
}
else
{
// prompt user with message sent!
// as we have the message object we can also display who the message
// was sent to etc
}
// finally dispose of the message
if (msg != null)
msg.Dispose();
}
By creating a fresh SMTP client each time this will allow you to send out emails simultaneously.
What you want to do is run the e-mail task on a separate thread so the main code can continue processing while the other thread does the e-mail work.
Here is a tutorial on how to do that: Threading Tutorial C#