I have two methods to send emails. One makes the UI stop while it sends the email, and the other one is supposed to be asynchronous, keeping the UI active (and in my use case, redirecting to another page later on) while the email is send in the background, on another thread. I am not too experienced with asynchronous functions, but I guess this was supposed to work.
My specific problem is:
This method sends the email
public static void sendEmail(string nameFrom, string passwordFrom, string to, string subject, string text, string smtpHost, string attachments = null, int port = 25)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(nameFrom, passwordFrom);
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(nameFrom);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
message.To.Add(to);
message.From = from;
message.Subject = subject;
message.Body = text;
message.IsBodyHtml = true;
smtp.Host = smtpHost;
smtp.Port = port;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = credentials;
if (attachments != null && attachments != "")
{
if (System.IO.File.Exists(attachments) == true)
{
System.Net.Mail.Attachment attFile = new System.Net.Mail.Attachment(attachments);
message.Attachments.Add(attFile);
}
}
smtp.Send(message);
}
This one doesn't
public static async Task sendEmailAsync(string nameFrom, string passwordFrom, string to, string subject, string text, string smtpHost, string attachments = null, int port = 25)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(nameFrom, passwordFrom);
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(nameFrom);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
message.To.Add(to);
message.From = from;
message.Subject = subject;
message.Body = text;
message.IsBodyHtml = true;
smtp.Host = smtpHost;
smtp.Port = port;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = credentials;
if (attachments != null && attachments != "")
{
if (System.IO.File.Exists(attachments) == true)
{
System.Net.Mail.Attachment attFile = new System.Net.Mail.Attachment(attachments);
message.Attachments.Add(attFile);
}
}
await smtp.SendMailAsync(message);
}
Why is the second one not sending the email and how can I fix it?