发送SMTP邮件错误:传输无法连接到服务器

时间:2014-02-03 09:06:31

标签: c# asp.net email

protected void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        MailMessage Msg = new MailMessage();
        Msg.From = txtFrom.Text;
        Msg.To = txtTo.Text;
        Msg.Subject = txtSubject.Text;
        Msg.Body = txtBody.Text;
        SmtpMail.SmtpServer = "1.20.72.1";
        SmtpMail.Send(Msg);
        Msg = null;
        Page.RegisterStartupScript("UserMsg", "<script>alert('Mail sent thank you...');if (alert) {window.location='SendMail.aspx';}</Script>");
    }
    catch (Exception ex)
    {
        msgLabel.Text = "Caught Exception." + ex;
    }
}

在上面帮助我点击Send我得到像这样的错误

抓到

Exception.System.Web.HttpException (0x80004005): The transport failed to connect to the server. 
---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. 
---> System.Runtime.InteropServices.COMException: The transport failed to connect to the server. 
--- End of inner exception stack trace --- 
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) 
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) 
at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) 
at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) 
at System.Web.Mail.SmtpMail.CdoSysHelper.Send(MailMessage message) at System.Web.Mail.SmtpMail.Send(MailMessage message) 
at MaiApp.Mail.btnSubmit_Click(Object sender, EventArgs e) in c:\Users\Riffaz\Documents\Visual Studio 2012\Projects\MaiApp\MaiApp\Mail.aspx.cs:line 28

1 个答案:

答案 0 :(得分:1)

在关于SmtpMail属性SmtpServer的文档中,MSDN说

  

获取或设置要用于发送的SMTP中继邮件服务器的名称   电子邮件。

相反,对于新的SmtpClient类,在description of the constructor中,它表示

  

包含主机名称或IP地址的字符串   用于SMTP事务。

所以我会尝试打电话

try 
{
    MailAddress from = new MailAddress(txtFrom.Text);
    MailAddress to = new MailAddress(txtTo.Text);
    MailMessage message = new MailMessage(from, to);
    message.Subject = txtSubject.Text;
    message.Body = txtBody.Text;
    SmtpClient client = new SmtpClient("1.20.72.1");
    client.Send(message);
}
catch (Exception ex) 
{
    msgLabel.Text = "Caught Exception." + ex;
}

此代码将使用SMTP流量的默认端口25,如果这不正确,则需要为SMTP流量配置正确的端口。
您的代码中还有其他问题。例如,您不向SMTP服务器提供任何凭据。现在看起来有点奇怪,很少有服务信任匿名用户。