This article describe how we can send async mail using ASP.Net
First Method takes "to","attachements","subject","body" as parameters and set within the logic itself.
You have to set all the credentials i.e "Username","password".
client.SendAsync(mailmessage, userState); => As this line gets execute running thread doesnt wait for the next instruction and it executes the next statement and so on.
And the following code make sense to callback the rest of logic:
- client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
So the Second Method does rest of the logic.
- public string SendMail(string to, string[] attachments, string subject, string Body = "")
- {
- string userState = "Mail State";
- MailMessage mailmessage = new MailMessage("[email protected]", to, subject, Body);
- SmtpClient client = new SmtpClient();
- client.Port = 587;
- client.Host = "smtp.gmail.com";
- client.EnableSsl = true;
- client.UseDefaultCredentials = false;
- client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
- client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
- NetworkCredential _NetworkCredentials = new NetworkCredential("[email protected]", "password");
- if (attachments != null)
- {
-
- foreach (string attachment
- in attachments)
- mailmessage.Attachments.Add(new System.Net.Mail.Attachment(attachment));
- }
- client.SendAsync(mailmessage, userState);
- return "0";
- }
- private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
- {
-
- String token = (string)e.UserState;
- if (e.Cancelled)
- {
-
- }
- if (e.Error != null)
- {
-
- }
- else
- {
-
- }
- }