在 Visual Studio 2005 中将旧代码从 System.Web.Mail 更新为 System.Net.Mail:发送电子邮件时出现问题
-
09-06-2019 - |
题
使用过时的 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 有关,这些版本之间的底层代码是否有一些变化?
没有任何异常被抛出。
其他提示
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")
我遇到了这个错误,但我相信它引发了异常。
你所做的一切都是正确的。这是我要检查的事情。
- 仔细检查 IIS 中的 SMTP 服务是否运行正常。
- 确保它没有被标记为垃圾邮件。
每当我们在发送电子邮件时遇到问题时,这些通常是最大的罪魁祸首。
另外,刚刚注意到您正在执行 MsgBox(例如 Message)。我相信他们阻止了 MessageBox 在服务包中运行 asp.net,所以它可能会出错,只是你可能不知道而已。检查您的事件日志。
我添加了邮件服务器的端口号,它开始偶尔工作,似乎是服务器出现问题并且发送消息出现延迟。感谢您的回答,它们都很有帮助!
不隶属于 StackOverflow