0

Here is method of Send Email thats Return Boolean

public  bool SendEmail()
{
    bool isSend = true;
    try
    {
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.Credentials = new NetworkCredential("kips321786@gmail.com","umerzaman100");
        smtp.EnableSsl = true;
        MailAddress to = new MailAddress("m.umer.zaman@gmail.com");
        MailAddress from = new MailAddress("kips321786@gmail.com");
        MailMessage mail = new MailMessage(from, to);
        check = to.ToString();
        mail.Subject = "This is a Test Mail ";
        mail.Body = "WoW Mail is Receive";
        lblStatus.Text=" Sending email...";
        smtp.Send(mail);
        Thread.Sleep(10000);
    }
    catch (Exception e)
    {
        check = e.Message.ToString();
        isSend = false;
    }
    return isSend;
}

This is my Mial Proccess method thats Async i have cancel button that prevent to send the Email what i should Right in the cancel buttonmethod

public  async void MailProccess(CancellationToken cancelToken =new CancellationToken())
{
    Task<bool> task2 = new Task<bool>(SendEmail);
    task2.Start();
    bool msg = await  task2;
    if (msg)
    {
        lblStatus.Text = "Your Email Send....";
    }
    else
    {
        lblStatus.Text = "Your Email not Send....";
    }
}

Here is my cancel button method

private void btnCancelEmail_Click(object sender, EventArgs e)
{
    cts.Cancel();
    lblStatus.Text = "Email Sending Cancel";
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Umer Zaman
  • 181
  • 3
  • 16
  • https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children – Hack Sep 22 '17 at 11:34
  • Yes it is Good but in my scenario i have separate Cancel Button How i will Do – Umer Zaman Sep 22 '17 at 11:45
  • This question was marked as duplicate before I could put in an answer unfortuantly. I think you are asking the wrong question here. I think what you should have asked was "How to cancel an email mid way" or something like that. Check out https://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.sendasynccancel(v=vs.110).aspx . You will need to make the Client a class variable or otherwise available to the cancel button and then on click make the call client.SendAsyncCancel() – Hack Sep 22 '17 at 11:55

1 Answers1

-3
try{
   smtp.Send(mail);
   isSend = true;
   }
catch(Exception ex)
   {
    isSend = false
   }

Please try this

  • 1
    this doesn't answer the question. he is asking how to cancel the sending of the mail mid way if the user clicks the cancel button after the task has started. – Hack Sep 22 '17 at 11:31