0

我试图弄清楚如何创建一个简单的联系页面以发送电子邮件。现在我只是在测试,但我没有收到任何错误消息。

这是我的代码:

protected void btnSend_Click(object sender, EventArgs e)
{
   MailMessage msg = new MailMessage();
   msg.To.Add(txtFrom.Text);
   msg.Subject = txtSubject.Text;
   msg.Body = txtMessage.Text;

   SmtpClient smtp = new SmtpClient("localhost");
   smtp.Send(msg);

   Response.Write("Your email was sent");
}
4

3 回答 3

2

您的本地主机上是否运行了 SMTP 服务?如果没有,您可以使用 Gmail 的 smtp 服务进行测试。

SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Credentials = new NetworkCredential("<your gmail login>", "<your gmail password>");
client.EnableSsl = true;
于 2013-11-04T23:30:39.887 回答
0

正如其他人指出的那样,您可能没有将 localhost 作为真正的邮件服务器。要获得更好的想法,请打开Tracing并将您的代码更改为类似这样的内容:

protected void btnSend_Click(object sender, EventArgs e) {
    Trace.Write("btnSend_Click initialized");
    string resp = "An unknown error occured.";
    using (MailMessage msg = new MailMessage()) {
        try {
            msg.To.Add(txtFrom.Text);
            msg.Subject = txtSubject.Text;
            msg.Body = txtMessage.Text;
            SmtpClient smtp = new SmtpClient("localhost");
            Trace.Write("smtp client created.");
            smtp.Send(msg);
            Trace.Write("smtp message sent.");
            resp = "Your message was sent.";
        } catch (Exception ex) {
            Trace.Warn("Smtp Error", ex.Message);
            resp = "There was an error sending your message.";
        }
    }
    Response.Write(resp);
    Trace.Write("btnSend_Click completed");
}
于 2013-11-04T23:48:44.520 回答
0

您必须像这样指定发件人地址:

msg.From = new MailAddress("noreply@noreply"); // Use a real address, of course

因为你没有得到异常,我想知道是否btnSend_Click被击中了......

其他要看的东西:

  1. txtFrom.Text是否在回发时被覆盖?您可能会在调试期间硬编码您的电子邮件地址。
  2. 尝试127.0.0.1代替localhost.
于 2013-11-05T02:04:09.967 回答