36

How to send a mail through mvc-3 asp.net using c#?

I have to send a forgot password so how can I do this? My code is below.

Model code..

 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 code..

  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("abc@gmail.com");
            msg.To.Add(user_email_address);
            msg.Subject = "Password";
            msg.Body = "Test1";
            msg.Priority = MailPriority.High;

            SmtpClient client = new SmtpClient();




            client.Credentials = new NetworkCredential("abc@gmail.com", "dip", "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();
        }

Here I fetched the password of user from database through entered email address..

View code..

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

   <%} %>

It gives me an error on these line

 client.Send(msg);

Error messege is:

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

How to solve it? thanks in advance

Dip
  • 778
  • 5
  • 13
  • 26
  • 32
    Please consider *not* emailing a recovery password. You should provide a link to reset a password on your website. – Mike Bailey Mar 09 '12 at 06:12
  • 5
    Yes, you should store passwords in a hashed, and not decipherable format. Check out Troy Hunt's [Everything you ever wanted to know about building a secure password reset feature](http://www.troyhunt.com/2012/05/everything-you-ever-wanted-to-know.html) article. – Akos Lukacs Mar 17 '13 at 16:04
  • 4
    OT, but there is a huge SQL injection vulnerability in this code. Consider what happens when I POST with user_email_address= `my_address_not_in_your_database@domain.com,' OR 'admin@yoursite.com`... – gregmac Aug 07 '13 at 19:15

8 Answers8

69

Import the System.Net.Mail namespace.

The code will look similar to this:

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("myemail@gmail.com");
mail.To.Add("recepient@gmail.com");
mail.Subject = "Password recovery";
mail.Body = "Recovering the password";

smtpServer.Send(mail);

P.S. You have a SQL injection vulnerability in the sample code. Use a SqlCommand object with parameters instead of String.Format().

Using SqlDataReader would be a lot more efficient to check for a record instead of populating a DataSet.

Dmitry S.
  • 8,373
  • 2
  • 39
  • 49
  • Hey, @Dmitry I implement your code but it giving me an error on line smtpServer.send(mail); like this error is :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. ub10sm724863igb.7 – Dip Mar 09 '12 at 06:35
  • You need to add a proper port and credentials for some servers. You would need the following info for the gmail smtp server – Dmitry S. Mar 09 '12 at 17:46
  • 5
    SmtpServer.Credentials = new System.Net.NetworkCredential(userName, password); SmtpServer.Port = 587; // Gmail works on this port – Dmitry S. Mar 09 '12 at 17:46
  • And I don't understand the reviewers here. I updated the code to add this important information about network credentials (which is important as it works different for an individual e-mail account and service e-mail acounts). However 3 reviewers rejected the update. @War10ck – Rohit Mar 10 '14 at 18:31
  • 1
    You should wrap the MailMessage and SmtpClient variable declarations in using() statements to properly dispose of them when complete. – Auri Rahimzadeh Aug 31 '14 at 23:10
  • With regard to the SQL Injection... you should use a parameterized query AND use ExecuteScalar(). – Auri Rahimzadeh Aug 31 '14 at 23:11
16

Have a look at MvcMailer

MvcMailer provides you with an ActionMailer style email sending NuGet Package for ASP.NET MVC 3/4. So, you can produce professional looking emails composed of your MVC master pages and views with ViewBag.

Dhaust
  • 5,470
  • 9
  • 54
  • 80
10

you can use this...

    public void SendEmail(string address, string subject, string message)
    {
        string email = "-your-id-@gmail.com";
        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);
    }
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
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("Mxolisi@gmail.com  ", "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("Mxolisi@gmail.com ", " 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("Mxolisi@gmail.com ", "Administrator");
            m.To.Add(to);
            SmtpClient smtp = new SmtpClient
            {
                Host = "pod51014.outlook.com",
                Port = 587,
                Credentials = new System.Net.NetworkCredential("Mxolisi@gmail.com ", "Dut324232"),
                EnableSsl = true
            };

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

        }

    }
}
Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Sqalo
  • 11
  • 2
1

i am using this for sending 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);
Syed Salman Raza Zaidi
  • 2,172
  • 9
  • 42
  • 87
0

You should turn on the SMTP service in Window 7 :

  • go to Control Panel > Programs
  • click "Turn window features ON or OFF"
  • click Internet Information Service and click OK
Yannick Blondeau
  • 9,465
  • 8
  • 52
  • 74
Arslan Bilal
  • 625
  • 2
  • 9
  • 17
  • This turns on SMTP server and has nothring to do with .NET. Besides, it is most likely that not allot of emails will be dleivered if you sendt emails from home or an uncofigured server (ie SPF, rDNS..etc etc) This answer is not correct. – Piotr Kula Oct 21 '14 at 09:59
0

when use smtp for gmail, remember put

smtpClient.UseDefaultCredentials = false;

before

smtpClient.Credentials = loginInfo;
Pham
  • 431
  • 3
  • 4
0

It look like you are trying to send emails through GMail's SMTP service, which this SO question already covers: Sending email in .NET through Gmail

The only thing that looks missing in your code is that you've set client.UseDefaultCredentials = true, I think you want to set this to false and provide your own credentials. I've never tried using GMail to send through emails, but I'm guessing you'll need to use a GMail account as your credentials in order to authenticate properly.

Community
  • 1
  • 1
Peter Monks
  • 4,219
  • 2
  • 22
  • 38