In this article I will explain with an example, how to send email in ASP.Net Core (.Net Core) MVC.
Mail Server Settings in Web.Config file
The Mail Server settings are saved in the SMTP section as shown below.
{
"Smtp": {
"Server": "smtp.gmail.com",
"Port": 587,
"DefaultCredentials": true,
"EnableSsl": true
}
}
Sending Email using Gmail SMTP
MailMessage class properties
Following are the required properties of the MailMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies. (If any)
BCC – Blind Carbon Copies. (If any)
Subject – Subject of the Email.
Body – Body of the Email.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SMTP class properties
Following are the properties of the SMTP class.
Host – SMTP Server URL. (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections. (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server. (Gmail: email address and password)
Port – Port Number of the SMTP server. (Gmail: 587)
Model
The Model class consists of the following properties.
public class EmailModel
{
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public IFormFile Attachment { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Net;
using System.Net.Mail;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside this Action method, the posted values are captured through the EmailModel class object. All the fetched values are set into an object of the MailMessage class except Attachment.
Setting Body of Email
The Body of the email is Text (Non HTML) hence the IsBodyHtml property of MailMessage class is set to FALSE.
Attaching File
The IFormFile is checked for Attachment and if it has File then the posted File is added as Attachment to the MailMessage class object.
Sending Email
Then, an object of the SmtpClient class is created and the values of Host, Port, EnableSsl and UseDefaultCredentials are fetched from the SMTP section of the AppSettings.json file and set to the respective properties of SmtpClient class along with the Credentials.
Finally, the
Send method is executed which sends the Email and a success message is set to a
ViewBag object.
public class HomeController : Controller
{
public IConfiguration Configuration { get; set; }
public HomeController(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(EmailModel model)
{
//Read SMTP section from AppSetting.json.
string host = this.Configuration.GetValue<string>("Smtp:Server");
int port = this.Configuration.GetValue<int>("Smtp:Port");
bool enableSsl = this.Configuration.GetValue<bool>("Smtp:EnableSsl");
bool defaultCredentials = this.Configuration.GetValue<bool>("Smtp:DefaultCredentials");
using (MailMessage mm = new MailMessage(model.Email, model.To))
{
mm.Subject = model.Subject;
mm.Body = model.Body;
mm.IsBodyHtml = false;
if (model.Attachment != null)
{
string fileName = Path.GetFileName(model.Attachment.FileName);
mm.Attachments.Add(new Attachment(model.Attachment.OpenReadStream(), fileName));
}
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = host;
smtp.Port = port;
smtp.EnableSsl = enableSsl;
smtp.UseDefaultCredentials = defaultCredentials;
NetworkCredential networkCred = new NetworkCredential(model.Email, model.Password);
smtp.Credentials = networkCred;
smtp.Send(mm);
}
}
ViewBag.Message = "Email sent.";
return View();
}
}
View
HTML Markup
Inside the View, the EmailModel class is declared as model for the View and ASP.Net TagHelpers in inherited.
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The HTML Form has been specified with enctype=“multipart/form-data” attribute as it is necessary for File Upload operation.
The Form consists of HTML TextBox, TextArea, FileUpload element and a Submit Button.
When the Submit Button is clicked, the Form gets submitted and the Model object is sent to the Controller.
Submitting the Form
Finally, the
ViewBag object is checked for NULL and if it is not NULL then the value of the object is displayed using
JavaScript Alert Message Box.
@model Send_Email_MVC_Core.Models.EmailModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index" enctype="multipart/form-data">
<table>
<tr>
<td style="width: 80px">To:</td>
<td><input type="text" asp-for="To" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Subject:</td>
<td><input type="text" asp-for="Subject" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td valign="top">Body:</td>
<td><textarea cols="20" rows="3" asp-for="Body"></textarea></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>File Attachment:</td>
<td><inputtype="file"asp-for="Attachment"/></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Gmail Email:</td>
<td><input type="text" asp-for="Email" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Gmail Password:</td>
<td><input type="password" asp-for="Password" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td></td>
<td><input type="submit" value="Send" /></td>
</tr>
</table>
</form>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Email Form
Received Email
Downloads