簡體   English   中英

如果包裝在 using() 中,SmtpClient.SendAsync() 不發送 email

[英]SmtpClient.SendAsync() not sending email if wrapped in using()

我有一個.Net5 應用程序,我正在嘗試使用 SmtpClient 發送電子郵件。 據我了解,我應該將其包裝在 Using 語句中

所以我有以下

using(SmtpClient client = new SmtpClient(host, port))
{
   ....my code.....
   client.SendAsync(message, userState);
}

然而,這成功了,但我從未收到 email。

如果我將代碼更改為

SmtpClient client = new SmtpClient(host, port);
....my code.....
client.SendAsync(message, userState);

然后我收到了 email。

我認為客戶端在 email 被正確發送之前被處理,但后來我認為“使用”應該正確處理?

處置客戶的最佳做法是什么? 此外,我可能需要使用相同的代碼發送多封電子郵件,因此我需要確保每次都創建新客戶端,以便在發送另一個 email 時不會丟棄它。

您需要使用回調來獲取 SendAsync 調用的結果。

此外,因為您在“使用”語句中,所以 SmtpClient 實例在它有機會完成請求之前被處置。

您會得到如下調用的結果:

    static bool mailSent = false;
    private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        // Get the unique identifier for this asynchronous operation.
         String token = (string) e.UserState;

        if (e.Cancelled)
        {
             Console.WriteLine("[{0}] Send canceled.", token);
        }
        if (e.Error != null)
        {
             Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
        } else
        {
            Console.WriteLine("Message sent.");
        }
        mailSent = true;
    }

        //.... in some other place in the code where your SmptClient lives
        client.SendCompleted += new
        SendCompletedEventHandler(SendCompletedCallback);
        // The userState can be any object that allows your callback
        // method to identify this send operation.
        // For this example, the userToken is a string constant.
    
        client.SendAsync(message, userState);
        //wait for the mail to be sent
        while(!mailSent)
        {
        }

並且基本上使用 SmtpClient 如果您請求結束之前不處置實例,則 SendAsync 可以工作。

基本上,您可能會在完成的事件中或通過等待 boolean 來處理實例。

這並不理想,但 SmtpClient class 又過時了。

該示例直接取自微軟的文檔SmtpClient

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM