我正在尝试弄清楚如何创建简单的联系页面以发送电子邮件。现在我只是测试,但我没有收到任何错误消息。
这是我的代码:
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");
}
答案 0 :(得分: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;
答案 1 :(得分: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");
}
答案 2 :(得分:0)
您必须指定一个From地址:
msg.From = new MailAddress("noreply@noreply"); // Use a real address, of course
因为你没有得到例外,我想知道btnSend_Click
是否会受到攻击......
其他要注意的事项:
txtFrom.Text
是否会在回发时被覆盖?您可以在调试期间对您的电子邮件地址进行硬编码。127.0.0.1
代替localhost
。