In this article I will explain with an example, how to send email with multiple attachments in ASP.Net Core MVC.
Mail Server Settings in AppSettings.json file
The mail server settings are saved in the Smtp section as shown below.
{
"Smtp": {
"Server": "smtp.gmail.com",
"Port": 587,
"EnableSsl": true,
"DefaultCredentials": true
}
}
Model
The Model class consists of the following properties.
Note: IFormFile is the new Class for Files in .Net Core. It is a replacement of HttpPostedFileBase class.
public class EmailModel
{
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public List<IFormFile> Attachments { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
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
This Action method handles the call made from the POST function from the View.
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).
When the Form is submitted, the posted values are captured through the EmailModel class object. All the fetched values are set into an object of the MailMessage class.
A FOR EACH loop is executed over the IFormFile and if the IFormFile has attachments then, all the attachments is added to the Attachments list of the MailMessage class object.
Then, an object of the SmtpClient class is created and the values of Host, Port, EnableSsl and DefaultCredentials are fetched from the Smtp section of the AppSettings.json file.
Finally, the email is sent using the Send function of the SmtpClient class object 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;
}
// GET: Home
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(EmailModel model)
{
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;
if (model.Attachments != null)
{
foreach (IFormFile attachment in model.Attachments)
{
string fileName = Path.GetFileName(attachment.FileName);
mm.Attachments.Add(new Attachment(attachment.OpenReadStream(), fileName));
}
}
mm.IsBodyHtml = false;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = host;
smtp.EnableSsl = enableSsl;
NetworkCredential networkCred = new NetworkCredential(model.Email, model.Password);
smtp.UseDefaultCredentials = defaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = port;
smtp.Send(mm);
ViewBag.Message = "Email sent.";
}
}
return View();
}
}
View
Inside the View, the EmailModel class is declared as Model for the View and ASP.Net TagHelpers is 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.
Inside the Form, there is an HTML Table which consists of some TextBoxes in which one TextBox type is set to file.
The Table also consists of a TextArea and a Submit button.
When the Submit Button is clicked, the Form gets submitted and the Model object is sent to the Controller.
@model Send_Email_Attachments_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 border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 80px">To:</td>
<td><input type="text" asp-for="To" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" asp-for="Subject" /></td>
</tr>
<tr>
<td valign="top">Body:</td>
<td><textarea cols="20" rows="3" asp-for="Body"></textarea></td>
</tr>
<tr>
<td>File Attachment:</td>
<td><input type="file" asp-for="Attachments" multiple="multiple" /></td>
</tr>
<tr>
<td>Gmail Email:</td>
<td><input type="text" asp-for="Email" /></td>
</tr>
<tr>
<td>Gmail Password:</td>
<td><input type="password" asp-for="Password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Send" /></td>
</tr>
</table>
<br/>
<span style="color:green">@ViewBag.Message</span>
</form>
</body>
</html>
Possible Errors
The following error occurs when you try to send email using Gmail credentials in your application.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Solution
Screenshots
The Form
The received Email
Downloads