Introduction
In this article, we will learn how to send emails using SMTP Server in ASP.NET MVC with Web API. There are many ways to send an email - SMTP, POP3, IMAP, Exchange Web Services, Outlook Interop, etc. Here, we will use SMTP (Gmail).
For sending an email via SMTP, the .NET framework includes a library System.Net.Mail namespace. Now, I will show how to do it step by step.
Step 1
Open Visual Studio and go to File » New » Project. Create a new project. Select Visual C# from templates and choose Web and give the project name as MailSendingWithWebApi and then click OK.
Step 2
Choose MVC from "Select a template" window and check Web API from "Add folders and core references for:" section and click OK.
Step 3
Now, create a new class in the Models folder and name it as EmailModel.cs.
Code for EmailModel.cs
- using System.ComponentModel.DataAnnotations;
-
- namespace MailSendingWithWebApi.Models
- {
- public class EmailModel
- {
- [Required, Display(Name = "Your name")]
- public string toname { get; set; }
- [Required, Display(Name = "Your email"), EmailAddress]
- public string toemail { get; set; }
- [Required]
- public string subject { get; set; }
- [Required]
- public string message { get; set; }
- }
- }
Step 4
Create a new Web API Controller in the Controllers folder and name it as EmailController. For that, right-click on the Controllers folder and click on Add --> Controller --> Web API 2 Controller- Empty --> Add.
Code for EmailController.cs
- using Newtonsoft.Json.Linq;
- using System.IO;
- using System.Net.Mail;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Http;
-
- namespace MailSendingWithWebApi.Controllers
- {
- [RoutePrefix("api/email")]
- public class EmailController : ApiController
- {
- [HttpPost]
- [Route("send-email")]
- public async Task SendEmail([FromBody]JObject objData)
- {
- var message = new MailMessage();
- message.To.Add(new MailAddress(objData["toname"].ToString() + " <" + objData["toemail"].ToString() + ">"));
- message.From = new MailAddress("Amit Mohanty <[email protected]>");
- message.Bcc.Add(new MailAddress("Amit Mohanty <[email protected]>"));
- message.Subject = objData["subject"].ToString();
- message.Body = createEmailBody(objData["toname"].ToString(), objData["message"].ToString());
- message.IsBodyHtml = true;
- using (var smtp = new SmtpClient())
- {
- await smtp.SendMailAsync(message);
- await Task.FromResult(0);
- }
- }
-
- private string createEmailBody(string userName, string message)
- {
- string body = string.Empty;
- using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("/htmlTemplate.html")))
- {
- body = reader.ReadToEnd();
- }
- body = body.Replace("{UserName}", userName);
- body = body.Replace("{message}", message);
- return body;
- }
- }
- }
Here, we use MailMessage Class to send mail. There are some minimum required properties of the MailMessage class that we have used here.
- From - Sender’s email address.
- To - Recipient(s) Email Address.
- CC - Carbon Copies (Optional). Put the email address(s) here if you are sending a copy for their information and you want everyone to explicitly see this.
- BCC - Blind Carbon Copies (Optional). Put the email address here if you are sending them a copy and you do not want the other recipients to see that you sent it to this contact.
- Subject - Subject of the Email.
- Body - Body of the Email.
- IsBodyHtml - Specify whether body contains text or HTML mark up.
Step 5
Now, modify the Index.cshtml page with the below code.
Code for Index.cshtml
- @model MailSendingWithWebApi.Models.EmailModel
- @{
- ViewBag.Title = "Test Email";
- }
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <h4>Send your message.</h4>
- <hr />
- <div class="form-group">
- @Html.LabelFor(m => m.toname, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.TextBoxFor(m => m.toname, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.toname)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.toemail, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.TextBoxFor(m => m.toemail, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.toemail)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.subject, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.TextBoxFor(m => m.subject, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.subject)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.message, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.TextAreaFor(m => m.message, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.message)
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" class="btn btn-default" value="Send" />
- </div>
- </div>
- }
Step 6
Then, go to the HomeController and add the below code for Index Post method.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Index(EmailModel model)
- {
- using (var client = new HttpClient())
- {
-
- client.BaseAddress = new Uri(Baseurl);
-
- client.DefaultRequestHeaders.Clear();
-
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
-
- HttpResponseMessage Res = await client.PostAsJsonAsync("api/email/send-email", model);
-
-
- if (Res.IsSuccessStatusCode)
- {
- return View("Success");
- }
- else
- {
- return View("Error");
- }
- }
- }
Step 7
After that, create two new view pages - Success and Error. If the email is sent successfully, it will redirect to the Success page; otherwise, it redirects to the Error page. For that, add the below code to HomeController.
- public ActionResult Success()
- {
- return View();
- }
-
- public ActionResult Error()
- {
- return View();
- }
Now, right-click on Success() and Error() and click on "Add View" like in the below images.
Step 8
Move to the Web.config file and add the below code.
- <system.net>
- <mailSettings>
- <smtp from = "[email protected]" >
- <network host="smtp.gmail.com"
- port="587"
- userName="[email protected]"
- password="yourmailpasswd"
- enableSsl="true" />
- </smtp>
- </mailSettings>
- </system.net>
Here, we are using SMTP Class to send the email.
SMTP Class
Following are the properties of the SMTP class.
- Host - SMTP Server URL (here we use smtp.gmail.com).
- EnableSsl - Specify whether your host accepts SSL Connections.
- Credentials - Valid login credentials for the SMTP server (userName: email address and password: email address password).
- Port - Port number of the SMTP server (For Gmail: 587).
Step 9
Now, save and run your project. It will look like the below, in the browser.
Step 10
Fill the fields and click on the Send button. When the Send button is clicked, the posted values are captured through the EmailModel class object and set into an object of the MailMessage class to send an email. If the email is successfully sent then it will redirect to the success page.
If you will get an error from the GMAIL Server, then first, you must check whether the Username and Password supplied are correct. If your Username and Password are correct but still you get an error, check your "Allows less secure apps" option of the given email. If this option is off, then turn it on. To check "Allows less secure apps" setting, first, log in to your Gmail account then visit the below link.
Link - https://myaccount.google.com/lesssecureapps
I hope this is useful for all readers. Happy Coding!