开发者

how to stop application from quiting before the mail is send through SmtpMailClient.SendAsync()

开发者 https://www.devze.com 2023-03-31 07:18 出处:网络
I have a issue with sending mail via SmtpMailClient.SendAsync(), i.e. if the application is closed immediately after SmtpMailClient.SendAsync(), mail开发者_如何学Go is not sent.

I have a issue with sending mail via SmtpMailClient.SendAsync(), i.e. if the application is closed immediately after SmtpMailClient.SendAsync(), mail开发者_如何学Go is not sent.

So how to force the app not to close till the callback ?

Thanks !!


The SmtpClient has a SendCompleted event. Here's a sample code on how to implement it: http://www.systemnetmail.com/faq/4.6.aspx

Depending on your platform, you need to implement some kind of an Application object which counts the pending SendAsync operations and only allow the application to end if they are 0.


Add a SendCompleted http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.sendcompleted.aspx event handler to your SmtpClient object.


I think the question is really: How do you intercept a quit command and defer it based on application state?

For WinForms:

protected override void OnFormClosing(FormClosingEventArgs e) 
{ 
    if (isSending) 
    { 
        quitOnSent = true; // make it so the quit will eventually happen
        e.Cancel = true; // prevent the quit for now
    } 
    base.OnFormClosing(e); 
} 

void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e)
{
    if(quitOnSent) this.Close(); // now quit
}


Finally did it by using a bool variable to find whether the mail is sent or not.

code:

   public static bool mailsent ;

   // I am not posting the mail sending code as its available every where.

    private void sendMailComplete(Object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {

        MailMessage msd = e.UserState as MailMessage;

        if (!e.Cancelled) 
        {
            MessageBox.Show("Cancelled");
        }
         if (e.Error != null)
        {
            MessageBox.Show("Error");

        }

        else
        {
            mailsent = true;
        }

    }

Now in the FormClosing event

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e){

        if (!mailsent)
        {
            MessageBox.Show("Please wait, Mail Sending in Process !!! ");
            e.Cancel = true;
        }
    }

Hope it helps !!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号