2012-03-09 7 views
37

Come inviare una mail tramite mvc-3 asp.net utilizzando C#?Come inviare e-mail da Asp.net Mvc-3?

Devo inviare una password dimenticata, quindi come posso fare? Il mio codice è di sotto.

Codice modello ..

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; } 
    } 
} 

Controller cod ..

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(); 
     } 

Qui Presi la password dell'utente dal database tramite l'indirizzo e-mail inserito ..

Visualizza codice ..

<% 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"/> 

    <%} %> 

Mi dà un errore sulla linea di questi

client.Send(msg); 

messege errore è:

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 

come risolverlo? grazie in anticipo

+32

perche * non * email una password di ripristino. Dovresti fornire un link per reimpostare una password sul tuo sito web. –

+5

Sì, è necessario memorizzare le password in formato hash e non decifrabile. Dai un'occhiata a Troy Hunt's [Tutto ciò che avresti sempre voluto sapere sulla creazione di una funzione di reimpostazione sicura della password] (http://www.troyhunt.com/2012/05/everything-you-ever-wanted-to-know.html). –

+4

OT, ma esiste un'enorme vulnerabilità di SQL injection in questo codice. Considera cosa succede quando I POST con user_email_address = '[email protected], 'OR' admin @ yoursite.com' ... – gregmac

risposta

69

Importare lo spazio dei nomi System.Net.Mail.

Il codice sarà simile a questo:

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); 

P.S. Hai una vulnerabilità di SQL injection nel codice di esempio. Utilizzare un oggetto SqlCommand con parametri anziché String.Format().

L'utilizzo di SqlDataReader sarebbe molto più efficiente per verificare la presenza di un record anziché compilare uno DataSet.

+0

Ehi, @Dmitry Implemento il tuo codice ma mi dà un errore sulla linea smtpServer.send (posta elettronica); come questo l'errore è: il server SMTP richiede una connessione sicura o il client non è stato autenticato. La risposta del server era: 5.7.0 Deve prima inviare un comando STARTTLS. ub10sm724863igb.7 – Dip

+0

È necessario aggiungere una porta e credenziali adeguate per alcuni server. Avresti bisogno delle seguenti informazioni per il server smtp di gmail –

+5

SmtpServer.Credentials = new System.Net.NetworkCredential (userName, password); SmtpServer.Port = 587; // Gmail funziona su questa porta –

16

Dai un'occhiata alla MvcMailer

MvcMailer fornisce un'email stile ActionMailer invio NuGet Pacchetto per ASP.NET MVC 3/4. Quindi, puoi produrre email dall'aspetto professionale composte dalle tue pagine master e visualizzazioni MVC con ViewBag.

1

Sto usando questo per l'invio di email, in 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

sembrare che stanno cercando di inviare e-mail tramite il servizio SMTP di GMail, che questa domanda SO copre già: Sending email in .NET through Gmail

L'unica cosa che sembra mancare nel tuo codice è che hai impostato client.UseDefaultCredentials = true, penso che tu voglia impostarlo su false e fornire le tue credenziali. Non ho mai provato a utilizzare GMail per inviare tramite e-mail, ma suppongo che per poter autenticare correttamente dovrai utilizzare un account GMail come credenziali.

0

Si dovrebbe attivare il servizio SMTP in Window 7:

  • andare a Pannello di controllo> Programmi
  • click "Turn finestra o disattivazione delle funzionalità"
  • clic su Internet Information Service e fare clic su OK
+0

Attiva il server SMTP e non ha nulla a che fare con .NET. Inoltre, è molto probabile che non verrà assegnato alcun invio di e-mail se si inviano email da casa o da un server non configurato (es. SPF, rDNS..etc ecc.). Questa risposta non è corretta. – ppumkin

11

è possibile utilizzare questo ...

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

quando l'uso smtp per Gmail, ricordate messo

smtpClient.UseDefaultCredentials = false;

prima

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; 

     } 

    } 
}