2013-09-16 35 views
0

我通過ASP.NET的發送電子郵件,當我試圖把他們在異步模式下,它沒有工作,arised錯誤: Failure sending mail. ---> System.InvalidOperationException: Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event.發送電子郵件在ASP異步失敗淨

這裏是我的代碼:

MailMessage message = new MailMessage(); 
    message.From = new MailAddress("[email protected]"); 
    message.To.Add(new MailAddress(to)); 
    message.Subject = subject; 
    message.Body = body; 

    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 
    SmtpServer.Port = 587; 
    SmtpServer.Credentials = new NetworkCredential(userName, pass); 
    SmtpServer.EnableSsl = true; 
    SmtpServer.Send(message); //sends successful 
    SmtpServer.SendCompleted += SmtpServer_SendCompleted; 
    SmtpServer.SendAsync(message, null); //failure sending 
在這個例子中
+0

@Arran,臨屋後不幫我。因爲它有關於線程和'背景'的解釋,但是我有一個內置函數不起作用。 –

+0

@Josh Mein,剛纔我注意到所有其他答案之間的答案,真的很難理解那裏的正確答案。 –

回答

2

我找到了答案。我需要在@page標籤添加Async="True"

<%@ Page Language="c#" Async="true" AutoEventWireup="false" CodeFile="TestHotmail.aspx.cs" Inherits="TestHotmail" %> 
+0

對不起,您顯然沒有在*兩個*關聯的問題中正確看待。這個答案在**都是**。無論如何,很高興你能對它進行排序。 – Arran

+0

@Arran,也許答案是在兩者中,但我不明白它從鏈接,因爲它不是很清楚,我在博客中找到答案:http://blog.ysatech.com/post/2009/11 /08/Asynchronous-operations-are-not-allowed-in-this-context.aspx –

0

.. http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx 沒有 SmtpServer.Send(消息); 之前 SmtpServer.SendAsync(message,null);

該文章還提到,您必須等待發送完成嘗試另一次發送之前。

所以也許包裝異步調用如果當SmtpServer.SendCompleted。

+0

在這裏,我寫在一起,但我試圖發送**只是**異步,並出現一個錯誤。 –