Share via


ASP.NET c#: How to send an email

Most of the times we have seen suggestion/complaint form in the footer of many websites but what if you want the same thing in your project?

There are two methods to implement this:

  1. Make a database and save the form details in that so when the site admin logins, he/she can see them.
  2. Generate an email from the code so you can get an email and can retrieve that on the go.

We will explain the second method here. This method will simply guide you how to send an email and then you can use this in any way you like.

First of all we created a form in html view of a mvc project which looks like this:

http://4.bp.blogspot.com/-vl1qkBzxu-U/VjEkiEBTlKI/AAAAAAAAALI/jYIJsh88D_Q/s640/Form.JPG

HTML for this form is:

@using (Html.BeginForm("email", "Home", FormMethod.Post))

        {

  <div class="row">

    <div class="col-lg-12">

    <form name="sentMessage" id="contactForm" novalidate>

      <div class="row">

      <div class="col-md-6">

        <div class="form-group">

        <input type="text" name="sname" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

        <p class="help-block text-danger"></p>

        </div>

        <div class="form-group">

        <input type="email" name="semail"class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

        <p class="help-block text-danger"></p>

        </div>

        <div class="form-group">

        <input type="tel" name="sphone"class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

        <p class="help-block text-danger"></p>

        </div>

      </div>

      <div class="col-md-6">

        <div class="form-group">

        <textarea class="form-control" name="smessage" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

        <p class="help-block text-danger"></p>

        </div>

      </div>

      <div class="clearfix"></div>

      <div class="col-lg-12 text-center">

        <div id="success"></div>

        

        <button type="submit" class="btn btn-xl" onclick="this.form.submit();">Send Message</button>

         

      </div>

      </div>

    </form>

    </div>

  </div>

}

If you copy and paste this html it wont work as desired due to the css. So dont get confused with the code this is just to guide you a bit, you can make any kind of form you like.

If you observe the start of HTML we have used

@using (Html.BeginForm("email", "Home", FormMethod.Post))

this is used to call the controller actionresult method when the user submits this form. "email" is the name of actionresult method and "Home" is the controller. That is the main thing where the whole stuff happens.

In controller there is a method and an actionmethod that calls that method.

   public async Task<ActionResult> email(FormCollection form)

  {

    var name = form["sname"];

    var email = form["semail"];

    var messages = form["smessage"];

    var phone = form["sphone"];

    var x = await SendEmail(name,email,messages,phone);

    if (x == "sent")

    ViewData["esent"]= "Your Message Has Been Sent";

    return RedirectToAction("Index");

  }

  private async Task<string> SendEmail(string name, string email, string messages, string phone)

  {

    var message = new MailMessage();

    message.To.Add(new MailAddress("abc@xyz.com"));  // replace with receiver's email id 

    message.From = new MailAddress("xyz@abc.com");  // replace with sender's email id

    message.Subject = "Message From" + email;

    message.Body = "Name: " + name + "\nFrom: " + email + "\nPhone: " + phone + "\n" + messages;

    message.IsBodyHtml = true;

    using (var smtp = new SmtpClient())

    {

    var credential = new NetworkCredential

    {

      UserName = "xyz@abc.com",  // replace with sender's email id

      Password = "*****"  // replace with password

    };

    smtp.Credentials = credential;

    smtp.Host = "smtp-mail.outlook.com";

    smtp.Port = 587;

    smtp.EnableSsl = true;

    await smtp.SendMailAsync(message);

    return "sent";

    }

  }

So whats happening here is that we have created an async task of actionresult type which is called when user clicks the submit button and values from the form are passed into it.

public async Task<ActionResult> email(FormCollection form)

Async is used when you have to wait for an action to complete before moving ahead. as this process requires some time so we need to use async type and this allows us to use await keyword in it.

private async Task<string> SendEmail(string name, string email, string messages, string phone)

this is a method which returns a string to tell the status. we have passed all the form values which we need in my email.

 message.To.Add(new MailAddress("abc@xyz.com"));  // replace with receiver's email id

here we have to write the email id on which we want to recieve the email

     message.From = new MailAddress("xyz@abc.com");  // replace with sender's email id

here goes the senders email id, we have used my id in both so we am sending an email from my one id to another which contains the users query/suggestion, contact, name and email so we can respond he later if we want to

     message.Subject = "Message From" + email;

here goes the subject, we have write the user's email in the subject, you can write anything you like

     message.Body = "Name: " + name + "\nFrom: " + email + "\nPhone: " + phone + "\n" + messages;

here goes the body, we have write users name, email, phone and message in the body. You can get the desired things according to your requirements and form fields.

   var credential = new NetworkCredential

    {

      UserName = "xyz@abc.com",  // replace with sender's email id

      Password = "*****"  // replace with password

    };

here you have to give your email id and password of that id which you are using to send email. so our code can login using these credentials.

 smtp.Credentials = credential;

    smtp.Host = "smtp-mail.outlook.com";

    smtp.Port = 587;

    smtp.EnableSsl = true;

these are the setting of hotmail/outlook. we was using my hotmail id as a sender so these work for that. If you are using live/outlook/hotmail you can use these ones but for other clients you can search Host and Port and replace these with those and it will work like a charm.