在 Visual Studio 2005 中将旧代码从 System.Web.Mail 更新为 System.Net.Mail:发送电子邮件时出现问题

StackOverflow https://stackoverflow.com/questions/52321

使用过时的 System.Web.Mail 发送电子邮件效果很好,代码片段如下:

 Public Shared Sub send(ByVal recipent As String, ByVal from As String, ByVal subject As String, ByVal body As String)
        Try
            Dim Message As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage
            Message.To = recipent
            Message.From = from
            Message.Subject = subject
            Message.Body = body
            Message.BodyFormat = MailFormat.Html
            Try
                SmtpMail.SmtpServer = MAIL_SERVER
                SmtpMail.Send(Message)
            Catch ehttp As System.Web.HttpException
                critical_error("Email sending failed, reason: " + ehttp.ToString)
            End Try
        Catch e As System.Exception
            critical_error(e, "send() in Util_Email")
        End Try
    End Sub

这是更新的版本:

Dim mailMessage As New System.Net.Mail.MailMessage()

        mailMessage.From = New System.Net.Mail.MailAddress(from)
        mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent))

        mailMessage.Subject = subject
        mailMessage.Body = body

        mailMessage.IsBodyHtml = True
        mailMessage.Priority = System.Net.Mail.MailPriority.Normal

        Try

            Dim smtp As New Net.Mail.SmtpClient(MAIL_SERVER)
            smtp.Send(mailMessage)

        Catch ex As Exception

            MsgBox(ex.ToString)

        End Try

我尝试了许多不同的变体,但似乎没有任何效果,我有一种感觉,这可能与 SmtpClient 有关,这些版本之间的底层代码是否有一些变化?

没有任何异常被抛出。

有帮助吗?

解决方案

我已经测试了您的代码,并且我的邮件已成功发送。假设您对旧代码使用相同的参数,我建议您的邮件服务器(MAIL_SERVER)正在接受该邮件,并且处理有延迟,或者它认为它是垃圾邮件并丢弃它。

我建议使用第三种方式发送消息(如果你勇敢的话,可以使用telnet),看看是否成功。

编辑:我注意到(从您随后的回答中)指定端口有一定帮助。您没有说明您是否使用端口 25 (SMTP) 或端口 587(提交)或其他端口。如果您还没有这样做,使用提交端口也可能有助于解决您的问题。

维基百科RFC4409 有更多详细信息。

其他提示

System.Net.Mail 库使用配置文件来存储设置,因此您可能只需要添加如下部分

  <system.net>
    <mailSettings>
      <smtp from="test@foo.com">
        <network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>

您是否尝试过添加

smtp.UseDefaultCredentials = True 

发送之前?

另外,如果您尝试更改会发生什么:

mailMessage.From = New System.Net.Mail.MailAddress(from)
mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent))

对此:

mailMessage.From = New System.Net.Mail.MailAddress(from,recipent)

——凯文·费尔柴尔德

您是否正在设置电子邮件的凭据?

smtp.Credentials = New Net.NetworkCredential("xyz@gmail.com", "password")

我遇到了这个错误,但我相信它引发了异常。

你所做的一切都是正确的。这是我要检查的事情。

  1. 仔细检查 IIS 中的 SMTP 服务是否运行正常。
  2. 确保它没有被标记为垃圾邮件。

每当我们在发送电子邮件时遇到问题时,这些通常是最大的罪魁祸首。

另外,刚刚注意到您正在执行 MsgBox(例如 Message)。我相信他们阻止了 MessageBox 在服务包中运行 asp.net,所以它可能会出错,只是你可能不知道而已。检查您的事件日志。

我添加了邮件服务器的端口号,它开始偶尔工作,似乎是服务器出现问题并且发送消息出现延迟。感谢您的回答,它们都很有帮助!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top