0

I send emails via Asp .net, When I tried to send them in async mode, it didnt work, arised an error: 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.

Here is my code:

    MailMessage message = new MailMessage();
    message.From = new MailAddress("chani.poz@gmail.com");
    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
Chani Poz
  • 1,413
  • 2
  • 21
  • 46
  • @Arran, Tha post don't help me. Because it has an explanation about thread and `background`, but I have a built in function that don't work. – Chani Poz Sep 16 '13 at 15:42
  • @Josh Mein, just now i notice that the answer in between all other the answers, really hard to understand the right answer there. – Chani Poz Sep 16 '13 at 16:42

2 Answers2

3

I found the answer. I need to add Async="True" in @page tag:

<%@ Page Language="c#" Async="true" AutoEventWireup="false" CodeFile="TestHotmail.aspx.cs" Inherits="TestHotmail" %>
Chani Poz
  • 1,413
  • 2
  • 21
  • 46
  • I'm sorry, you clearly didn't look correctly in the *two* questions linked. That answer is in **both**. Regardless, glad you got it sorted. – Arran Sep 16 '13 at 16:28
  • @Arran, Maybe the answer is in both, but I didn't understand it from the links because it is not very clear, I found the answer in blog: http://blog.ysatech.com/post/2009/11/08/Asynchronous-operations-are-not-allowed-in-this-context.aspx – Chani Poz Sep 16 '13 at 16:35
0

in this example.. http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx there is no SmtpServer.Send(message); prior to SmtpServer.SendAsync(message, null);

The article also mentions that you have to wait for send to complete before attempting another send.

So maybe wrap the async call in an if when SmtpServer.SendCompleted.

FlemGrem
  • 814
  • 4
  • 9