articles » current » asp-net-core » send-gmail

ASP.NET Core: Send GMail from Web App

Send Gmail from ASP.NET Core web application using C#

This article requires ASP.NET Core.

It is very easy to send emails through a Gmail account using ASP.NET Core. For this to work successfully, the "less secure apps" Gmail setting must be enabled. This does not present any security problems as long as the gmail account uses a unique password.

Create a new ASP.NET Core MVC Web Application with "Gmail" as its name for this example.

Create a new C# class file and save it to the project's root folder as Gmail.cs.

// Gmail.cs
using System;
using System.Net.Mail;

namespace Gmail
	public class Email
		public static string Send(string Subject, string Body, bool IsHtml, string AttachmentPath)
				string GmailAccount = ""; // must change ""
				string GmailPassword = "********"; // must change to Gmail account password
				string ToEmails = ""; // this is the addresses to send the email to; can be the same Gmail account or another email address; separate multiple emails with commas

				MailMessage mail = new MailMessage(GmailAccount, ToEmails);
				mail.Subject = Subject;
				mail.IsBodyHtml = IsHtml;
				mail.Body = Body;
				if (!string.IsNullOrWhiteSpace(AttachmentPath))
					Attachment attachment = new Attachment(AttachmentPath);
					mail.Priority = MailPriority.High; // optional

				SmtpClient smtp = new SmtpClient("", 587);
				smtp.EnableSsl = true;
				smtp.UseDefaultCredentials = false;
				smtp.Credentials = new System.Net.NetworkCredential(GmailAccount, GmailPassword);
				return ""; // return nothing when it is successful
			catch (Exception ex)
				return "An error occured while sending your message. " + ex.Message;

Modify the HomeController, located in the HomeController.cs file, to look like this:

 // HomeController.cs
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Gmail.Models;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Http; // NOTE: CODE ADDED HERE

namespace Gmail.Controllers
	public class HomeController : Controller
		private readonly ILogger<HomeController> _logger;

		public HomeController(ILogger<HomeController> logger)
			_logger = logger;

		public IActionResult Index()
			return View();

		public IActionResult Privacy()
			return View();

		[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
		public IActionResult Error()
			return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });

		public IActionResult Email()
			return View();

		public async Task<IActionResult> Email(IFormCollection form)
			return await Task.Run(() =>
				var message = form["name"] + ' ' + form["email"] + ' ' + form["message"];
				var isHtml = !string.IsNullOrEmpty(form["ishtml"]);
				var result = Gmail.Email.Send("Email from Website", message, isHtml, null);
				if (string.IsNullOrEmpty(result))
					result = "Your message was sent successfully";
				return View(model: result);

Create "Email.cshtml" to have the email form, and do not forget the AntiForgeryToken which must be submitted with the form.

@model string
	ViewData["Title"] = "Email using Gmail";

	<p class="alert-danger">@Model</p>
	<form method="post">
		<input type="text" name="name" required maxlength="50" autocomplete="off" placeholder="your name" /><br />
		<input type="email" name="email" required autocomplete="off" placeholder="your email" /><br />
		<textarea name="message" required placeholder="your message"></textarea><br />
		<input type="checkbox" name="ishtml" value="yes" />HTML?<br />
		<button type="submit">Send</button>

Run the web application using Ctrl+F5 or under the "Debug" menu option select "Start Without Debugging." Navigate the browser to /Home/Email and try to send an email. Check the Gmail account inbox for a message about "less secure apps" and enable this function if the emails are not going through.

Coding Video

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.