2013-06-24 191 views
2

(成品RESULT去編輯/ EDIT AT BOTTOM)ASP.net剃鬚刀 - 使用Gmail SMTP網站發送電子郵件

正如標題狀態我想使用Gmail網站發送電子郵件SMTP如ASP.net教程中所述:http://www.asp.net/web-pages/tutorials/email-and-search/11-adding-email-to-your-web-site

在早期解決ISAPI.dll處理程序映射錯誤之後,Webmatrix錯誤控制檯中沒有更多錯誤,只是「GET」和「POST」操作的成功標記;但是,該網頁正在返回try catch錯誤,「電子郵件未發送....」

在SQL Server管理器中,我嘗試查看是否爲服務器和管理員角色設置了郵件,但我可以'沒有看到代理屬性,我明白,因爲我有快速版SQL Management Studio。也就是說,如果服務器角色或郵件設置出現問題,肯定會生成錯誤消息?

有人可以請客氣一下,快速瀏覽SMTP設置和整體代碼,請提供錯誤或建議嗎?

(順便說一句,我在示例代碼改變了我的電子郵件地址和密碼,重複的webmail.username和webmail.from我的電子郵件地址)

感謝。

這裏是EmailRequest.cshtml

 @{ 

    } 

    <!DOCTYPE html> 
    <html> 
    <head> 
     <title>Request for Assistance</title> 
    </head> 
    <body> 
     <h2>Submit Email Request for Assistance</h2> 
     <form method="post" action="ProcessRequest.cshtml"> 
     <div> 
      Your name: 
      <input type="text" name="customerName" /> 
     </div> 

     <div> 
      Your email address: 
      <input type="text" name="customerEmail" /> 
     </div> 

     <div> 
      Details about your problem: <br /> 
      <textarea name="customerRequest" cols="45" rows="4"></textarea> 
     </div> 

     <div> 
      <input type="submit" value="Submit" /> 
     </div> 
     </form> 
    </body> 
    </html> 

**Here is ProcessRequest.cshtml** 

     @{ 
     var customerName = Request["customerName"]; 
     var customerEmail = Request["customerEmail"]; 
     var customerRequest = Request["customerRequest"]; 
     var errorMessage = "true"; 
     var debuggingFlag = false; 
     try { 
      // Initialize WebMail helper 
      WebMail.SmtpServer = "smtp.gmail.com"; 
      WebMail.EnableSsl = true; 
      WebMail.SmtpPort = 465; 
      WebMail.UserName = "MY EMAIL ADDRESS.com"; 
      WebMail.Password = "MYPASSWORD"; 
      WebMail.From = "MY EMAIL ADDRESS.com"; 

      // Send email 
      WebMail.Send(to: customerEmail, 
       subject: "Help request from - " + customerName, 
       body: customerRequest 
      ); 
     } 
     catch (Exception ex) { 
      errorMessage = ex.Message; 
     } 
    } 
    <!DOCTYPE html> 
    <html> 
    <head> 
     <title>Request for Assistance</title> 
    </head> 
    <body> 
     <p>Sorry to hear that you are having trouble, <b>@customerName</b>.</p> 
     @if(errorMessage == ""){ 
      <p>An email message has been sent to our customer service 
      department regarding the following problem:</p> 
      <p><b>@customerRequest</b></p> 
     } 
     else{ 
      <p><b>The email was <em>not</em> sent.</b></p> 
      <p>Please check that the code in the ProcessRequest page has 
       correct settings for the SMTP server name, a user name, 
       a password, and a "from" address. 
      </p> 
      if(debuggingFlag){ 
       <p>The following error was reported:</p> 
       <p><em>@errorMessage</em></p> 
      } 
     } 
    </body> 
    </html> 
____________________________________________________ 

編輯:

感謝您的幫助邁克和格克汗。今天早上,我再仔細看看。果然,昨晚從網頁發送了兩封電子郵件;因此,在某些時候所有的因素都是正確的。

我曾嘗試過端口25,465和587,但是,我正在按照教程和'不是代碼'。該教程在我看來有點誤導,並造成混亂 - 我正在錯誤的收件箱中尋找電子郵件。人們會認爲通常會將問題報告發送給主機,而不是報告問題的用戶。

此外,即使電子郵件正在發送,try catch錯誤仍然顯示。當然,錯誤信息應該通過發出錯誤來激活。錯誤消息似乎只有在[var errorMessage =「true」;]設置爲true時纔會出現。

我錯過了什麼?任何人都可以請解釋本教程如何嘗試捕獲方法的作品?

無論如何,這一切都有效 - 我總是發現邁克的評論令人放心。

我使用另一個教程將代碼下載到了一個頁面,並添加了一些表單驗證,然後修改了代碼,以便將電子郵件發送給主機而不是用戶。

這是新的EmailRequest。CSHTML:

@{ 

    Layout = "/_SiteLayout.cshtml"; 
    Page.Title = "Compare"; 

    Validation.RequireField("emailAddress", "customerName is required."); 
    Validation.RequireField("emailSubject", "customerEmail is required."); 
    Validation.RequireField("emailBody", "customerRequest is required."); 

     var message = ""; 
     var companyname = Request.Form["emailAddress"]; 
     var contactname = Request.Form["emailSubject"]; 
     var employeecount = Request.Form["emailBody"]; 


    try{ 
     if (IsPost && Validation.IsValid()) { 

     // Send email 
     WebMail.Send(to:"ADMIN-EMAIL-ADDRESS.COM", 
      subject: Request.Form["emailSubject"], 

      body: "Help request from - " + Request.Form["customerName"] + " - " + "Email Subject - " + Request.Form["emailSubject"] + " - " + "Customer email - " + Request.Form["emailAddress"] 
      ); 
      message = "Email sent!"; 
     } 
    } 
    catch(Exception ex){ 
     message = "Email could not be sent!"; 
    } 
} 
<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8" /> 
    <title>Test Email</title> 

       <style type="text/css"> 
      .validation-summary-errors {font-weight:bold; color:red; font-size: 11pt;} 
      .validation-summary-valid { 
    display: none; 
} 

     </style> 

    </head> 
    <body> 
    <h1>Test Email</h1> 
    <form method="post"> 
     @Html.ValidationSummary("Errors with your submission:") 

     <p> 
     <label for="customerName">Name:</label> 
     <input type="text" name="customerName" value="@Request.Form["customerName"]" /> 


     </p> 

     <p> 
     <label for="emailAddress">Email address:</label> 
     <input type="text" name="emailAddress" value="@Request.Form["emailAddress"]" /> 


     </p> 
     <p> 
     <label for="emailSubject">Subject:</label> 
     <input type="text" name="emailSubject" value="@Request.Form["emailSubject"]" /> 

     </p> 
     <p> 
     <label for="emailBody">Text to send:</label><br/> 
     <textarea name="emailBody" rows="6"></textarea> 

     </p> 
    <p><input type="submit" value="Send!" /></p> 
    @if(IsPost){ 
     <p>@message</p> 
    } 
    </form> 
    </body> 
</html> 

最後,這裏是_AppStart代碼一起去,我昨天沒有發佈例如:

@{ 
     WebSecurity.InitializeDatabaseConnection("StarterSite", "UserProfile", "UserId", "Email", true); 

     // WebMail.SmtpServer = "mailserver.example.com"; 
     // WebMail.UserName = "[email protected]"; 
     // WebMail.Password = "your-password"; 
     // WebMail.From = "[email protected]"; 
     // WebMail.EnableSsl = true; (add this if smtp is encrypted) 
     // WebMail.SmtpPort = 587; 
    } 

編輯/ EDIT

我在在提交之後在textarea框中保留數據/值有問題以及驗證textarea框。更多的研究提醒了我,在這種情況下,兩個「必需」屬性並提供了一個整潔的工具提示。

因此,我已經剝離了保留文本框值並驗證了表單的前面的代碼,並使用「required」屬性代替 - 更加整潔。

此外,處理代碼和成功消息現在已內置到電子郵件請求頁面中,因此不再需要ProcessRequest.cshtml頁面。

下面是一個聯繫表格的完成代碼,用於向靜態電子郵件地址發送請求 - 除非您在頁面中添加郵件服務器驗證,否則不要忘記您還需要使用_AppStart頁面代碼 - 兩者都需要。但是,請注意,在用戶能夠查看它們的頁面中添加服務器電子郵件設置是不安全的。我建議使用_AppStart頁面作爲以Asp.net中的下劃線開頭的文件。Razor無法在線查看。

@{ 

    Layout = "/_SiteLayout.cshtml"; 
    Page.Title = "Compare"; 

    var message = ""; 
    var companyname = Request.Form["emailAddress"]; 
    var contactname = Request.Form["emailSubject"]; 
    var employeecount = Request.Form["emailBody"]; 


    try{ 
     if (IsPost && Validation.IsValid()) { 

     // Send email 
     WebMail.Send(to:"ADMIN EMAIL.COM", 
      subject: Request.Form["emailSubject"], 

      body: "Help request from - " + Request.Form["customerName"] + " - " + "Email Subject - " + Request.Form["emailSubject"] + " - " + "Customer email - " + Request.Form["emailAddress"] 
      ); 
      message = "Email sent!"; 
     } 
    } 
    catch(Exception ex){ 
     message = "Email could not be sent!"; 
    } 
} 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title>Test Email</title> 


</head> 

    <body> 
    <h1>Test Email</h1> 

    <form method="post"> 

     <p> 
     <label for="customerName">Name:</label> 
     <input type="text" name="customerName" required /> 
     </p> 

     <p> 
     <label for="emailAddress">Email address:</label> 
     <input type="text" name="emailAddress" required /> 
     </p> 
     <p> 
     <label for="emailSubject">Subject:</label> 
     <input type="text" name="emailSubject" required /> 

     </p> 

     <p> 
     <label for="emailBody">Text to send:</label><br/> 
     <textarea name="emailBody" rows="6" required></textarea> 
     </p> 

    <p><input type="submit" value="Send!" /></p> 
    @if(IsPost){ 
     <p>@message</p> 
    } 
    </form> 
    </body> 
</html> 
+0

上面的代碼應該可以正常工作。只需將SMTP端口更改爲587. –

回答

2

我已經寫了很久以前的項目的代碼。嘗試這個。

public void SendEmail(string from, string to, string subject, string body) 
{ 
    string host = "smtp.gmail.com"; 
    int port = 587; 

    MailMessage msg = new MailMessage(from, to, subject, body); 
    SmtpClient smtp = new SmtpClient(host, port); 

    string username = "[email protected]"; 
    string password = "1234567890"; 

    smtp.Credentials = new NetworkCredential(username, password); 
    smtp.EnableSsl = true; 
    smtp.UseDefaultCredentials = false; 

    try 
    {  
     smtp.Send(msg); 
    } 
    catch (Exception exp) 
    { 
     //Log if any errors occur 
    } 
} 
+0

感謝您的答覆。當我再次打開我的電腦時,我會在早上與您的代碼一起去,我會讓你知道我如何繼續。 – DaniB

0

如果您想用剃鬚刀豐富電子郵件正文,您可以使用Mailzory。另外,您可以從here下載nuget包。用法很簡單:

// template path 
var viewPath = Path.Combine("Views/Emails", "hello.cshtml"); 
// read the content of template and pass it to the Email constructor 
var template = File.ReadAllText(viewPath); 

var email = new Email(template); 

// set ViewBag properties 
email.ViewBag.Name = "Johnny"; 
email.ViewBag.Content = "Mailzory Is Funny"; 

// send email 
var task = email.SendAsync("[email protected]", "subject"); 
task.Wait() 
相關問題