PROWAREtech

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

ASP.NET Core: Send Gmail from Web App

Send Gmail from a 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)
		{
			try
			{
				string GmailAccount = "your_gmail_account@gmail.com"; // must change "your_gmail_account@gmail.com"
				string GmailPassword = "********"; // must change to Gmail account password
				string ToEmails = "mailbox@domain.com"; // 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.Attachments.Add(attachment);
					mail.Priority = MailPriority.High; // optional
				}

				SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
				smtp.EnableSsl = true;
				smtp.UseDefaultCredentials = false;
				smtp.Credentials = new System.Net.NetworkCredential(GmailAccount, GmailPassword);
				smtp.Send(mail);
				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 });
		}


		// NOTE: FOLLOWING CODE ADDED
		public IActionResult Email()
		{
			return View();
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public IActionResult Email(IFormCollection form)
		{
			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";
}

<div>
	<h1>@ViewData["Title"]</h1>
	<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>
		@Html.AntiForgeryToken()
	</form>
</div>

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.

Also, if the web application is on a cloud service, then it probably will not work properly due to Google's security of Gmail. In this case, use the cloud email service. An example is SES (Simple Email Service) if using Amazon Web Services.

Coding Video

https://youtu.be/YGN-LXn8RKI


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.
CLOSE