2012-03-09 77 views
37

如何使用c#通過mvc-3 asp.net發送郵件?如何從Asp.net Mvc-3發送電子郵件?

我必須發送一個忘記的密碼,所以我該怎麼做? 我的代碼如下。

型號代碼..

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; 

namespace TelerikLogin.Models.ViewModels 
{ 
    public class ForgotPassword 
    { 
     public int user_id { get; set; } 
     public string user_login_name { get; set; } 
     public string user_password { get; set; } 

     [Required] 
     [Display(Name="Email Address : ")] 
     public string user_email_address { get; set; } 
    } 
} 

控制器代碼..

public ActionResult ForgotPassword() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ActionResult ForgotPassword(string user_email_address) 
     { 
      SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\MVC3\TelerikLogin\TelerikLogin\App_Data\Login.mdf;Integrated Security=True;User Instance=True"); 

      DataTable dt1 = new DataTable(); 

      string strQuery = string.Format("SELECT user_password FROM [user_master] WHERE user_email_address='{0}'",user_email_address); 
      conn.Open(); 
      SqlDataAdapter da1 = new SqlDataAdapter(strQuery, conn); 
      da1.Fill(dt1); 
      conn.Close(); 

      if (dt1.Rows.Count > 0) 
      { 

MailMessage msg = new MailMessage(); 

      msg.From = new MailAddress("[email protected]"); 
      msg.To.Add(user_email_address); 
      msg.Subject = "Password"; 
      msg.Body = "Test1"; 
      msg.Priority = MailPriority.High; 

      SmtpClient client = new SmtpClient(); 




      client.Credentials = new NetworkCredential("[email protected]", "disha", "smtp.gmail.com"); 
      client.Host = "smtp.gmail.com"; 
      client.Port = 587; 
      client.DeliveryMethod = SmtpDeliveryMethod.Network; 
      client.EnableSsl = true; 
      client.UseDefaultCredentials = true; 

      client.Send(msg); 


       return RedirectToAction("About", "Home"); 
      } 
      return View(); 
     } 

這裏我端來一從通過輸入的電子郵件地址數據庫用戶的密碼..

查看代碼..

<% using (Html.BeginForm("ForgotPassword", "Account", FormMethod.Post)) 
    { %> 

    <%: Html.LabelFor(m => m.user_email_address) %> 
    <%: Html.TextBox("user_email_address")%> 
     <%: Html.ValidationSummary(true) %> 

<input type="submit" value="Submit"/> 

    <%} %> 

這使我對這些行

client.Send(msg); 

錯誤messege是一個錯誤:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. x1sm1264662igc.16 

如何解決呢? 在此先感謝

+32

請考慮*不*電子郵件恢復密碼。您應該提供一個鏈接來重置您網站上的密碼。 – 2012-03-09 06:12:35

+5

是的,你應該將密碼存儲爲散列且不可辨認的格式。查看Troy Hunt的[你想知道的關於構建安全密碼重置功能的所有內容](http://www.troyhunt.com/2012/05/everything-you-ever-wanted-to-know.html)文章。 – 2013-03-17 16:04:59

+4

OT,但此代碼中存在巨大的SQL注入漏洞。請考慮當我使用user_email_address ='[email protected]'或'admin @ yoursite.com'進行POST時會發生什麼...... – gregmac 2013-08-07 19:15:54

回答

69

導入System.Net.Mail命名空間。

的代碼將類似於此:

MailMessage mail = new MailMessage(); 

SmtpClient smtpServer = new SmtpClient("smtp.gmail.com"); 
smtpServer.Credentials = new System.Net.NetworkCredential("userName", "password"); 
smtpServer.Port = 587; // Gmail works on this port 

mail.From = new MailAddress("[email protected]"); 
mail.To.Add("[email protected]"); 
mail.Subject = "Password recovery"; 
mail.Body = "Recovering the password"; 

smtpServer.Send(mail); 

附:示例代碼中存在SQL注入漏洞。使用參數SqlCommand而不是String.Format()

使用SqlDataReader會更有效地檢查記錄而不是填充DataSet

+0

嘿,@Dmitry 我執行您的代碼,但它給我一個線路上的錯誤 smtpServer.send (郵件);像這樣 錯誤是:SMTP服務器需要安全連接或客戶端未通過身份驗證。服務器響應是:5.7.0必須首先發出STARTTLS命令。 ub10sm724863igb.7 – Dip 2012-03-09 06:35:22

+0

您需要爲某些服務器添加適當的端口和憑據。您需要以下信息Gmail郵件服務器 – 2012-03-09 17:46:40

+5

SmtpServer.Credentials = new System.Net.NetworkCredential(userName,password); SmtpServer.Port = 587; // Gmail在此端口上工作 – 2012-03-09 17:46:48

16

看一看MvcMailer

MvcMailer提供了一個的ActionMailer風格電子郵件發送NuGet包ASP.NET MVC的3/4。因此,您可以使用ViewBag製作由您的MVC母版頁和視圖組成的專業外觀電子郵件。從下面的鏈接繼續發送電子郵件在MVC3

1

我使用這個用於發送電子郵件,在ASP.net MVC3

System.Web.Helpers.WebMail.SmtpServer = smtp_server; 
      System.Web.Helpers.WebMail.SmtpPort = smtp_port; 
      System.Web.Helpers.WebMail.EnableSsl = true; 
      System.Web.Helpers.WebMail.From = "fromaddress"; 
      StringBuilder sb = new StringBuilder(); 
      sb.Append("<table><tr><td>");    
      sb.Append(msg);      
      sb.Append("</td></tr></table>"); 
      string body = sb.ToString(); 
      string To = toemail; 
      System.Web.Helpers.WebMail.Send(To,subject, body); 
0

它看起來像你正嘗試通過GMail的SMTP服務發送電子郵件,這個問題已經涵蓋了:Sending email in .NET through Gmail

你的代碼中唯一看起來缺少的是你已經設置了client.UseDefaultCredentials = true,我想你想把它設置爲false並提供你自己的憑證。我從來沒有嘗試過使用GMail發送電子郵件,但我猜你需要使用GMail帳戶作爲憑證才能正確進行身份驗證。

0

你應該打開SMTP服務窗口7:

  • 進入控制面板>程序
  • 點擊「打開窗口功能打開或關閉」
  • 單擊Internet信息服務,然後單擊確定
+0

這打開了SMTP服務器,並沒有與.NET做。此外,如果您發送來自家中的電子郵件或未經配置的服務器(如SPF,rDNS等等),則很可能不會收到所有電子郵件的分配。此答案不正確。 – ppumkin 2014-10-21 09:59:03

11

您可以使用此...

public void SendEmail(string address, string subject, string message) 
    { 
     string email = "[email protected]"; 
     string password = "put-your-GMAIL-password-here"; 

     var loginInfo = new NetworkCredential(email, password); 
     var msg = new MailMessage(); 
     var smtpClient = new SmtpClient("smtp.gmail.com", 587); 

     msg.From = new MailAddress(email); 
     msg.To.Add(new MailAddress(address)); 
     msg.Subject = subject; 
     msg.Body = message; 
     msg.IsBodyHtml = true; 

     smtpClient.EnableSsl = true; 
     smtpClient.UseDefaultCredentials = false; 
     smtpClient.Credentials = loginInfo; 
     smtpClient.Send(msg); 
    } 
0

時使用SMTP的Gmail,記得把

smtpClient.UseDefaultCredentials = false;

smtpClient.Credentials = loginInfo; 
1
Using Systems.Net.Mail; 
// POST: /Account/Register 
//Here's a simple Mail(MVC4) 

     public async Task<ActionResult> Register(RegisterViewModel model) 
     { 
      Mail email= new Mail(); 
      if (ModelState.IsValid) 
      { 
       var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email }; 
       var result = await UserManager.CreateAsync(user, model.Password); 
       if (result.Succeeded) 
       { 
        email.to = new MailAddress(model.Email); 
        email.body = "Hello " + model.Firstname + " your account has been created <br/> Username: " + model.UserName + " <br/>Password: " + model.Password.ToString() + " <br/> change it on first loggin"; 
        ViewBag.Feed = email.reg(); 


        await SignInAsync(user, isPersistent: false); 


        return RedirectToAction("Index", "Home"); 

       } 
       else 
       { 
        AddErrors(result); 
       } 
      } 

      // If we got this far, something failed, redisplay form 
      return View(model); 
     } 




//Business Logic(this Is you Email Class) 




Using Systems.Net.Mail; 


public class Mail 

    { 
     public MailAddress to { get; set; } 
     public MailAddress from { get; set; } 
     public string sub { get; set; } 
     public string body { get; set; } 




     public string reg() 
     { 
      string feed = "Registration Successful"; 
      var m = new System.Net.Mail.MailMessage() 
      { 
       Subject = "", 
       Body = body, 
       IsBodyHtml = true 
      }; 
      m.From = new MailAddress("[email protected] ", "Administrator"); 
      m.To.Add(to); 
      SmtpClient smtp = new SmtpClient 
      { 
       Host = "pod51014.outlook.com", 
       //Host = "smtp-mail.outlook.com", 
       Port = 587, 
       Credentials = new System.Net.NetworkCredential("[email protected] ", " Dut324232"), 
       EnableSsl = true 
      }; 

      try 
      { 
       smtp.Send(m); 
       // feed = ""; 
      } 
      catch (Exception e) 
      { 

      } 

      return feed; 

     } 
     public string fogot() 
     { 
      string feedback = ""; 

      var m = new System.Net.Mail.MailMessage() 
      { 
       Subject = "Reset Password PIN", 
       Body = body, 
       IsBodyHtml = true 
      }; 
      m.From = new MailAddress("[email protected] ", "Administrator"); 
      m.To.Add(to); 
      SmtpClient smtp = new SmtpClient 
      { 
       Host = "pod51014.outlook.com", 
       Port = 587, 
       Credentials = new System.Net.NetworkCredential("[email protected] ", "Dut324232"), 
       EnableSsl = true 
      }; 

      try 
      { 
       smtp.Send(m); 
       feedback = "Check your email for PIN"; 
      } 
      catch (Exception e) 
      { 
       feedback = "Message not sent" + e.Message; 
      } 
      return feedback; 

     } 

    } 
}