在 Asp 网络中异步发送电子邮件失败

本文关键字:电子邮件 失败 异步 Asp 网络 | 更新日期: 2023-09-27 18:31:26

我通过Asp .net发送电子邮件,当我尝试以异步模式发送电子邮件时,它不起作用,出现错误: 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.

这是我的代码:

    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

在 Asp 网络中异步发送电子邮件失败

我找到了答案。我需要@page标签中添加Async="True"

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

在这个例子中。http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx没有 SmtpServer.Send(message);之前 SmtpServer.SendAsync(message, null);

文章还提到,在尝试再次发送之前,您必须等待发送完成

因此,当SmtpServer.SendComplete时,可以将异步调用包装在if中。