Send Email with Attachment in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application

Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish

Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Contact}/{action=Index}/{id?}");
            });
        }
    }
}

Select Project and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select App Settings File item and click Add button to Finish

In appsettings.json file and new configurations as below:

{
  "Gmail": {
    "Host": "smtp.gmail.com",
    "Port": 587,
    "Username": "Your Gmail",
    "Password": "Password of your gmail",
    "SMTP": {
      "starttls": {
        "enable": true
      }
    }
  }
}

To send email with google mail server, we need to change the mail security configuration as follows: Open link: https://myaccount.google.com/u/1/lesssecureapps and switch Allow less secure apps to ON

Create new folder named Helpers. In this folder, create new class named MailHelper.cs as below:

using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;

namespace LearnASPNETCoreMVC5.Helpers
{
    public class MailHelper
    {
        private IConfiguration configuration;

        public MailHelper(IConfiguration _configuration)
        {
            configuration = _configuration;
        }

        public bool Send(string from, string to, string subject, string content, List<string> attachments)
        {
            try
            {
                var host = configuration["Gmail:Host"];
                var port = int.Parse(configuration["Gmail:Port"]);
                var username = configuration["Gmail:Username"];
                var password = configuration["Gmail:Password"];
                var enable = bool.Parse(configuration["Gmail:SMTP:starttls:enable"]);

                var smtpClient = new SmtpClient
                {
                    Host = host,
                    Port = port,
                    EnableSsl = enable,
                    Credentials = new NetworkCredential(username, password)
                };

                var mailMessage = new MailMessage(from, to);
                mailMessage.Subject = subject;
                mailMessage.Body = content;
                mailMessage.IsBodyHtml = true;
                if(attachments != null)
                {
                    foreach(var attachment in attachments)
                    {
                        mailMessage.Attachments.Add(new Attachment(attachment));
                    }
                }

                smtpClient.Send(mailMessage);

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

Create new folder named Models. In Models folder, create new entity class as below:

Create new class named Product.cs as below:

namespace LearnASPNETCoreMVC5.Models
{
    public class Contact
    {
        public string Name { get; set; }

        public string Phone { get; set; }

        public string Email { get; set; }

        public string Address { get; set; }

        public string Subject { get; set; }

        public string Content { get; set; }
    }
}

Create new folder named Controllers. In this folder, create new controller named ProductController.cs as below:

using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using LearnASPNETCoreMVC5.Helpers;
using LearnASPNETCoreMVC5.Models;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("contact")]
    public class ContactController : Controller
    {
        private IConfiguration configuration;

        private IWebHostEnvironment webHostEnvironment;

        public ContactController(IConfiguration _configuration, IWebHostEnvironment _webHostEnvironment)
        {
            configuration = _configuration;
            webHostEnvironment = _webHostEnvironment;
        }

        [Route("")]
        [Route("~/")]
        [Route("index")]
        public IActionResult Index()
        {
            return View("Index", new Contact());
        }

        [HttpPost]
        [Route("send")]
        public IActionResult Send(Contact contact, IFormFile[] attachments)
        {
            var body = "Name: " + contact.Name + "<br>Address: " + contact.Address + "<br>Phone: " + contact.Phone + "<br>";
            var mailHelper = new MailHelper(configuration);
            List<string> fileNames = null;
            if (attachments != null && attachments.Length > 0)
            {
                fileNames = new List<string>();
                foreach (IFormFile attachment in attachments)
                {
                    var path = Path.Combine(webHostEnvironment.WebRootPath, "uploads", attachment.FileName);
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        attachment.CopyToAsync(stream);
                    }
                    fileNames.Add(path);
                }
            }
            if (mailHelper.Send(contact.Email, configuration["Gmail:Username"], contact.Subject, body, fileNames))
            {
                ViewBag.msg = "Sent Mail Successfully";
            }
            else
            {
                ViewBag.msg = "Failed";
            }
            return View("Index", new Contact());
        }
    }
}

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Create new folder named Views. In this folder, create new folder named Contact. Create new view named Index.cshtml as below:

@model LearnASPNETCoreMVC5.Models.Contact

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Contact</h3>
    @ViewBag.msg
    <form method="post" enctype="multipart/form-data" asp-controller="contact" asp-action="send">
        <table>
            <tr>
                <td>Name</td>
                <td><input type="text" asp-for="Name" /></td>
            </tr>
            <tr>
                <td>Phone</td>
                <td><input type="text" asp-for="Phone" /></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="text" asp-for="Email" /></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><input type="text" asp-for="Address" /></td>
            </tr>
            <tr>
                <td>Subject</td>
                <td><input type="text" asp-for="Subject" /></td>
            </tr>
            <tr>
                <td valign="top">Content</td>
                <td><textarea asp-for="Content" rows="5" cols="20"></textarea></td>
            </tr>
            <tr>
                <td>Attachments</td>
                <td><input type="file" name="attachments" multiple="multiple" /></td>
            </tr>
            <tr>
                <td valign="top">&nbsp;</td>
                <td><input type="submit" value="Send"></td>
            </tr>
        </table>
    </form>

</body>
</html>

Access Index action in Contact controller with following url: http://localhost:48982/Contact/Index

Output

Enter email information and select the attachment. Click Send button to send email.