在Visual Studio 2005中将旧版代码从System.Web.Mail更新到System.Net.Mail:发送电子邮件时出现问题
时间:2020-03-05 18:50:11 来源:igfitidea点击:
使用过时的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有关,这些版本之间的基础代码是否有所更改?
没有异常被抛回。
解决方案
回答
我们是否尝试过添加
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)
-凯文·费尔柴尔德(Kevin Fairchild)
回答
我们已经测试了代码,并成功发送了邮件。假设我们对旧代码使用了相同的参数,我建议邮件服务器(MAIL_SERVER)正在接受该邮件,并且处理过程有所延迟,或者认为该邮件是垃圾邮件并丢弃了。
我建议我们使用第三种方式发送消息(如果感到勇敢,请使用telnet),然后查看是否成功。
编辑:我注意到(从后续答案),指定端口有所帮助。我们没有说要使用端口25(SMTP)还是端口587(提交)或者其他功能。如果我们尚未这样做,则使用疏泄端口也可能有助于解决问题。
Wikipedia和rfc4409有更多详细信息。
回答
我们是否正在设置电子邮件的凭据?
smtp.Credentials = New Net.NetworkCredential("[email protected]", "password")
我有此错误,但是我认为它引发了异常。
回答
System.Net.Mail库使用配置文件来存储设置,因此我们可能只需要添加这样的部分
<system.net> <mailSettings> <smtp from="[email protected]"> <network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" /> </smtp> </mailSettings> </system.net>
回答
我们所做的一切都是正确的。这是我要检查的东西。
- 仔细检查IIS中的SMTP服务是否正在正确运行。
- 确保它没有被标记为垃圾邮件。
每当我们在发送电子邮件时遇到问题时,这些通常是最大的罪魁祸首。
另外,只是注意到我们正在做MsgBox(ex.Message)。我相信他们阻止了MessageBox在Service Pack中使用asp.net,因此它可能会出错,我们可能不知道。检查事件日志。
回答
我添加了邮件服务器的端口号,它偶尔会开始工作,这似乎是服务器有问题,并且邮件发送延迟了。感谢回答,他们都很有帮助!