我是一名新的ASP.NET开发人员,我正在开发一个项目,管理员/系统可以在该项目中向用户发送电子邮件。由于我不希望管理员等到系统发送电子邮件,我计划使用SendAsync方法。
但是,我得到一个非常奇怪的错误
"发现了SmtpExecption:发送邮件失败。"
我无法解决它。
为了您的信息,我使用的是.NET Framework 4。
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
Mailer mail = new Mailer();
string senderE = ConfigurationManager.AppSettings["EmailID"].ToString();
string senderName = "Test User"
string recipientName = "TestSender";
string subject = txtSubject.Text;
string body = txtMessage.Text;
mail.SendAsync(senderE, senderName, recipient, recipientName, subject, body);
lblInfo.Text = "sent successfully :)";
Response.Redirect("Test.aspx");
}
catch
{
lblInfo.Text = "Error!!!";
}}
这是我的自定义Mailer类的SendAsync方法代码:
public void SendAsync(string sender, string senderName, string recipient, string recipientName, string subject, string body)
{
var message = new MailMessage()
{
From = new MailAddress(sender, senderName),
Subject = subject,
Body = body,
IsBodyHtml = true
};
message.To.Add(new MailAddress(recipient, recipientName));
try
{
var client = new SmtpClient();
client.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
string userState = "Test";
client.SendAsync(message, userState);
}
catch (Exception ex)
{
//handle exeption
throw ex;
}
finally
{
//clean up.
message.Dispose();
}
}
public static void MailDeliveryComplete(object sender, AsyncCompletedEventArgs e)
{
string message = "";
// Get the unique identifier for this asynchronous operation.
MailMessage mail = e.UserState as MailMessage;
if (e.Error != null)
{
//handle error
message = "Error " + e.Error.ToString() + " occurred";
}
else if (e.Cancelled)
{
//handle cancelled
message = "Send canceled for mail with subject " + mail.ToString();
}
else
{
//handle sent email
message = "Mail sent successfully";
}
}
那我该怎么办呢?
更新#1:
顺便说一句,我正在保存Web.Config文件中的所有SMTP配置。以下是设置:
<system.net>
<mailSettings>
<smtp from="My Gmail Account" deliveryMethod="Network">
<network enableSsl="true" host="smtp.gmail.com" port="587" userName="Username" password="Password" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>
更新#2: 在尝试了不同的建议之后,我将Async = True添加到了Page Directive,我收到了一条新的错误消息:
异步模块或处理程序在异步时完成 手术还在等待。
我调试了代码,这次调试器进入MailDeliveryMethod并从以下块中抛出此错误:
if (e.Error != null)
{
//handle error
message = "Error " + e.Error.ToString() + " occurred";
}
有关我为何会遇到此类错误的想法吗?