Sending Email Using Gmail Server in ASP.NET Core MVC

This guide will walk you through the steps to send an email using the Gmail server in an ASP.NET Core MVC application. We will use the MailKit and MimeKit libraries to handle the email functionality.

Prerequisites

  • Visual Studio 2019 or later
  • .NET Core SDK 3.1 or later
  • A Gmail account (with 2FA enabled)

Step 1. Create an ASP.NET Core MVC Project

  1. Open Visual Studio and create a new project.
  2. Select "ASP.NET Core Web Application" and click "Next".
  3. Name your project and click "Create".
  4. Select "Web Application (Model-View-Controller)" and ensure that ".NET Core" and "ASP.NET Core 3.1 or later" are selected. Click "Create".

Step 2. Install Required NuGet Packages

Install the MailKit and MimeKit packages which will help in sending emails.

  1. Open the NuGet Package Manager Console from Tools > NuGet Package Manager > Package Manager Console.
  2. Run the following commands.
Install-Package MailKit
Install-Package MimeKit

Step 3. Configure SMTP Settings

Add your Gmail SMTP settings in the appsettings.json file.

{
  "SmtpSettings": {
    "Server": "smtp.gmail.com",
    "Port": 587,
    "SenderName": "Your Name",
    "SenderEmail": "[email protected]",
    "Username": "[email protected]",
    "Password": "your-app-specific-password"
  }
}

To generate an app-specific password, follow these steps.

  1. Go to your Google Account
  2. Security Settings
    • Navigate to the "Security" section.
  3. App Passwords
    • Under "Signing in to Google," find "App passwords."
    • You might need to sign in again.
    • Select "App passwords."
  4. Generate an app password
    • Select the app (e.g., Mail) and the device (e.g., Windows Computer) from the dropdown.
    • Click "Generate."
    • Google will provide a 16-character password.
  5. Update Your Configuration
    • Use this 16-character password in your appsettings.json instead of your normal Google account password.

Step 4. Create the Email Service

Create a service to handle the email-sending logic. Add a new class EmailService.cs to your project.

using MimeKit;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
namespace EmailSendingInAspNetCoreMVC.Services
{
    public class EmailService
    {
        private readonly IConfiguration _configuration;
        public EmailService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public async Task SendEmailAsync(string toEmail, string subject, string message)
        {
            var emailMessage = new MimeMessage();
            emailMessage.From.Add(new MailboxAddress(_configuration["SmtpSettings:SenderName"], _configuration["SmtpSettings:SenderEmail"]));
            emailMessage.To.Add(new MailboxAddress("", toEmail));
            emailMessage.Subject = subject;
            emailMessage.Body = new TextPart("plain") { Text = message };
            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(_configuration["SmtpSettings:Server"], int.Parse(_configuration["SmtpSettings:Port"]), MailKit.Security.SecureSocketOptions.StartTls);
                await client.AuthenticateAsync(_configuration["SmtpSettings:Username"], _configuration["SmtpSettings:Password"]);
                await client.SendAsync(emailMessage);
                await client.DisconnectAsync(true);
            }
        }
    }
}

Step 5. Register for the Email Service

Register the EmailService in the Startup.cs file.

using EmailSendingInAspNetCoreMVC.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<EmailService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

Step 6. Create the EmailViewModel

Add a new class EmailViewModel.cs to your Models folder.

namespace EmailSendingInAspNetCoreMVC.ViewModels
{
    public class EmailViewModel
    {
        public string? ToEmail { get; set; }
        public string? Subject { get; set; }
        public string? Message { get; set; }
    }
}

Step 7. Create the Email Controller

Add a new controller EmailController.cs to handle the email sending requests.

using EmailSendingInAspNetCoreMVC.Sevices;
using EmailSendingInAspNetCoreMVC.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace EmailSendingInAspNetCoreMVC.Controllers
{
    public class EmailController : Controller
    {
        private readonly EmailService _emailService;

        public EmailController(EmailService emailService)
        {
            _emailService = emailService;
        }
        [HttpGet]
        public IActionResult SendEmail()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> SendEmail(EmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                await _emailService.SendEmailAsync(model.ToEmail, model.Subject, model.Message);
                ViewBag.Message = "Email sent successfully!";
            }
            return View(model);
        }
    }
}

Step 8. Create the Email View

Create a new view SendEmail.cshtml in the Views/Email folder.

@model EmailViewModel
@{
    ViewData["Title"] = "Send Email";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<form asp-action="SendEmail" method="post">
    <div>
        <label asp-for="ToEmail"></label>
        <input asp-for="ToEmail" type="email" required />
        <span asp-validation-for="ToEmail"></span>
    </div>
    <div>
        <label asp-for="Subject"></label>
        <input asp-for="Subject" type="text" required />
        <span asp-validation-for="Subject"></span>
    </div>
    <div>
        <label asp-for="Message"></label>
        <textarea asp-for="Message" required></textarea>
        <span asp-validation-for="Message"></span>
    </div>
    <div>
        <input type="submit" value="Send Email" />
    </div>
</form>
@if (ViewBag.Message != null)
{
    <p>@ViewBag.Message</p>
}

Step 9. Add Validation Scripts

Ensure that validation scripts are included in your _Layout.cshtml.

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>

Step 10. Run the Application

  1. Build and run your application.
  2. Navigate to /Email/SendEmail.
  3. Fill out the form and send an email.

Conclusion

By following this guide, you will successfully integrate email-sending functionality into your ASP.NET Core MVC application using the Gmail SMTP server. Utilizing `MailKit` and `MimeKit` libraries ensures secure and efficient handling of emails. Setting up an `EmailService`, creating an `EmailViewModel`, and configuring an `EmailController` with a corresponding view will provide a complete solution for sending emails. Generating an application-specific password for Gmail ensures compatibility with accounts that have two-factor authentication enabled. This setup enhances your application's functionality and enables effective communication with users.

GitHub Project Link: https://github.com/SardarMudassarAliKhan/EmailSendingInAspNetCoreMVC


Similar Articles