有没有办法看看System.Net.Mail是否有效

esk*_*ski 4 c# asp.net email

我正在使用System.Net.Mail发送电子邮件,如下所示:

MailMessage message = new MailMessage();

message.From = new MailAddress("foo@foo.com");
message.To.Add(new MailAddress("foobar@foobar.com"));


message.Subject = "Hello";
message.Body = "This is a nice body..";

SmtpClient client = new SmtpClient();
client.Send(message);
Run Code Online (Sandbox Code Playgroud)

我怎么知道电子邮件是否已发送,我可以用if句子来查看吗?那会是什么样子?

mar*_*c_s 6

您可能希望将SMTP调用包装到一个try...catch块中 - 这样您就可以轻松捕获可能发生的任何明显的SMTP相关错误:

try
{
   SmtpClient client = new SmtpClient();
   client.Send(message);
}
catch(Exception exc)
{
   // log the error, update your entry - whatever you need to do 
}
Run Code Online (Sandbox Code Playgroud)

这将处理最明显的错误,例如

  • 找不到SMTP服务器
  • SMTP服务器没有响应
  • SMTP拒绝您发送(例如,因为您没有提供任何或有效的凭据)

一旦SMTP服务器收到您的消息,它就不在您的.NET手中....您实际上做不了多少(除了检查SMTP服务器的日志是否有错误).

如果您想检查并查看您的SMTP邮件是否"已发送",您还可以将这些代码行添加到应用程序的app.config(或web.config)中,并让.NET将您的邮件放入目录(如EML文件):

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="C:\temp\mails"/>
      </smtp>
    </mailSettings>
  </system.net>
Run Code Online (Sandbox Code Playgroud)

您的邮件现在将C:\temp\mails作为EML文件存储到目录中,您可以查看它们并检查它们是否应该如此.