2013-11-04 104 views
0

我想弄清楚如何創建一個簡單的聯繫頁面以發送電子郵件。現在我只是測試,但我沒有收到任何錯誤消息。使用c發送電子郵件#

這裏是我的代碼:

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

發生了什麼事/錯? – jzm

+2

我的猜測是'localhost'不是一個真正的SMTP服務器或中繼點。將其替換爲真實的SMTP服務器地址,它應該可以工作。 – James

+0

@James說過的話或者你可能需要某種憑證。看看[這個SO問題](http://stackoverflow.com/questions/2766928/how-to-set-username-and-password-for-smtpclient-object-in-net) – Icemanind

回答

0

正如其他人指出的那樣,您可能沒有本地主機作爲真正的郵件服務器。爲了得到一個更好的主意,打開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"); 
} 
+0

啓用頁面跟蹤和重新編寫我的代碼,但仍然沒有得到一個錯誤。 –

+0

@TroyBryant嗯。假設你知道如何讀取跟蹤日誌,這也許意味着該功能永遠不會開火?嘗試在'protected void'行下面添加一個'Trace.Write(「函數調用」);'並再次運行它。不知道我曾經見過一個沉默的smtp失敗,所以也許它只是沒有得到調用。 – JClaspill

+0

@TroyBryant在上面的例子中添加了更多的追蹤,以便找出它可能死去的地方。 – JClaspill

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; 
+0

不,我不只是需要一些測試 –

0

您必須指定發件人地址是這樣的:

msg.From = new MailAddress("[email protected]"); // Use a real address, of course 

因爲你沒有得到一個例外,我不知道是否btnSend_Click被擊中在所有...

其他的事情來看待:

  1. 您的txtFrom.Text在回發中被覆蓋?您可能在調試期間硬編碼您的電子郵件地址。
  2. 嘗試127.0.0.1而不是localhost