Im trying to send mail using SendAsync method of SmtpClient.
But the SendCompleted event doesnt fire, though Im getting mails (after around 20 minutes delay!)
Googling it says, that MailMessage object is Disposed (using statement) before SendCompleted fires
I will be using the mailsend bool variable to test if mail has been sent (from where i will call the SendMail function)
Help!
private void SendMail()
{
client = new SmtpClient(mailConfig.Server, mailConfig.Port);
using (oMessage = new MailMessage() { From = new MailAddress(MailFrom, FromName, Encoding.UTF8) })
{
if (MailTo.Count == 1)
oMessage.To.Add(new MailAddress(MailTo[0], GDMS.Utilities.Classes.CurrentUser.CurrentUserName));
else
{
foreach (string s in MailTo)
oMessage.To.Add(new MailAddress(s));
}
oMessage.Subject = Subject;
if (CC != null && CC.Count > 0)
{
foreach (string s in CC)
oMessage.CC.Add(s);
}
if (!String.IsNullOrEmpty(HTMLBody))
{
oMessage.Body = HTMLBody;
oMessage.IsBodyHtml = true;
}
else
if (!String.IsNullOrEmpty(TextBody))
{
oMessage.Body = TextBody;
oMessage.IsBodyHtml = false;
}
if (BCC != null && BCC.Count > 0)
{
foreach (string s in BCC)
oMessage.CC.Add(s);
}
oMessage.BodyEncoding = Encoding.UTF8;
oMessage.SubjectEncoding = Encoding.UTF8;
oMessage.Priority = MailPriority.High;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(mailConfig.Username, mailConfig.Password);
if (mailConfig.Server.ToUpper().Contains("GMAIL"))
client.EnableSsl = true;
client.SendCompleted += new SendCompletedEventHandler(MailSendingComplete);
try
{
client.SendAsync(oMessage, "Sending Mail");
}
catch (Exception ex) { string msg = ex.Message; }
finally
{
mailSent = true;
}
}
}
private void MailSendingComplete(object sender, AsyncCompletedEventArgs e)
{
String token = (string)e.UserState;
if (e.Cancelled)
{
if (SendMailCompleted != null)
{
SendMailCompleted(this, string.Format("[{0}] Send canceled.", token));
}
}
if (e.Error != null)
{
if (SendMailCompleted != null)
{
SendMailCompleted(this, string.Format("[{0}] {1}", token, e.Error.Message));
}
}
else
{
if (SendMailCompleted != null)
{
SendMailCompleted(this, "Message sent.");
}
}
mailSent = true;
}