Click here to Skip to main content
14,330,776 members

Send Email Using SendGrid Email Service with an Attachment

Rate this:
4.54 (4 votes)
Please Sign up or sign in to vote.
4.54 (4 votes)
8 Oct 2019CPOL
This article will walk you through the creation of ASP.NET Core MVC web application with C# language and send an email using SendGrid Email Service.

Image 1

Photo by Austin Distel on Unsplash

Introduction

In a modern web application, email notification or verification has now become a major and important part of the application. Using email service, we can ensure application user registration, reset password, mobile number verification, etc. verification process very smoothly, quickly and so secure way. Newsletters, Promotion and Shipping Notifications task can also have been done by using email service as well.
Therefore in any application, alarm email notification, security verification process and enable or set something new email notification, we can make sure using email service.

In this article, I will explain with details, how to send an email from ASP.NET Core MVC web application using Sendgrid email service. I will write a Sendgrid email service as well for send an email using C# language and by installing Sendgrid nuget package manager.

Prerequisite

Good knowledge of C# language, ASP.NET Core MVC application and .NET CLI.

Background

Let's move to this demonstration and create an ASP.NET Core MVC web application. But before moving to the practical demonstration, let's understand the objective of this demonstration which tells what exactly will be covered in this article. So, here is the objective as follows:

  1. Create a SendGrid account
  2. Get API key from SendGrid account which already created
  3. Create project
  4. Code implementation
  5. Conclusion

Create a SendGrid Account

Sendgrid is a cloud based email service that ensures reliable email delivery, scalability, and real time service analysis using the SendGrid application dashboard. SendGrid API helps in delivering your important emails over SMPT or HTTP.
You can create an free account from Sendgrid website.

Image 2

After successfully creating the SendGrid account, you can create SendGrid email service API key which is required in the application implementation.

SendGrid Dashboard: Create or get API Key from here.

Image 3

Plan and Pricing

You can send 40,000 emails for first 30 days, then 100/day forever. For more details, please visit the Sendgrid website.

Image 4

Advantage of SendGrid

  1. 24 hours customer support
  2. Using dashboard, you can track Spam Reports, mail bounced back and other features as well.
  3. You can set daily/monthly mailing functionality.
  4. If server down, then you can put email service in queues.

Implementation

Let's first create an ASP.NET Core MVC web Application from .NET Core CLI.

$ dotnet new sln -n SendGridDotNetCore
$ dotnet new mvc -n SendGridDotNetCore
$ dotnet sln SendGridDotNetCore.sln add SendGridDotNetCore/SendGridDotNetCore.csproj

Install nuget package from Visual Studio,
> Install-Package Sendgrid -Version 9.10.0
From .NET CLI,
> dotnet add package Sendgrid --version 9.12.0

API Key and Email Info

In ASP.NET resource file, I put API key and send email related all info there so that it can access and edit in real-time execution.

Image 5

Build and Run

$ dotnet build
$ dotnet run
$ dotnet watch run

Publish and Run

$ dotnet publish -o ./publish
$ dotnet AutoMapperDemo.dll

Send Email Status

Here in application UI, showing the email delivery details status.

Image 6

Email Service Interface

public interface ISendGridEmailSender
{
    Task<Tuple<string, string, string>> Execute(string filePath);
}

Email Service Interface Implementation

public async Task<Tuple<string, string, string>> Execute(string filePath)
{
try
{
    var apiKey = EmailComponents.apiKey;
    var client = new SendGridClient(apiKey);
    var messageEmail = new SendGridMessage()
    {
        From = new EmailAddress(EmailComponents.fromEmail, EmailComponents.fromEmaliUserName),
        Subject = EmailComponents.Subject,
        PlainTextContent = EmailComponents.plainTextContent,
        HtmlContent = EmailComponents.htmlContent
    };

    messageEmail.AddTo(new EmailAddress
                      (EmailComponents.emailTo, EmailComponents.emailToUserName));
    var bytes = File.ReadAllBytes(filePath);
    var file = Convert.ToBase64String(bytes);
    messageEmail.AddAttachment("Voucher Details Report.pdf", file);
    var response = await client.SendEmailAsync(messageEmail);
    return new Tuple<string, string, string>
     (response.StatusCode.ToString(),response.Headers.ToString(),response.Body.ToString());
}
catch (Exception ex)
{
   throw ex;
}
}

Add Attachment in Email Boday

var messageEmail = new SendGridMessage();
var bytes = File.ReadAllBytes(filePath);
var file = Convert.ToBase64String(bytes);
messageEmail.AddAttachment("Voucher Details Report.pdf", file);

Controller

public class SendEmailController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
ISendGridEmailSender _ISendGridEmailSender;
public SendEmailController(IHostingEnvironment hostingEnvironment, 
                           ISendGridEmailSender ISendGridEmailSender)
{
    _hostingEnvironment = hostingEnvironment;
    _ISendGridEmailSender = ISendGridEmailSender;
}

// GET: SendEmail
public ActionResult Index()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> SendMail()
{
    var filePath = _hostingEnvironment.ContentRootPath + @"/ProjectNotes/VoucherDetails.pdf";
    var result = await _ISendGridEmailSender.Execute(filePath);
    Thread.Sleep(3000);
    ViewBag.SendGridStatusCode = result.Item1;
    ViewBag.SendGridHeaders = result.Item2.Replace("\r\n", " <***> ");
    ViewBag.SendGridBody = result.Item3.Replace("\r\n", " <***> ");
    return await Task.Run(() => View());
}
}

Startup

services.AddTransient<ISendGridEmailSender, SendGridEmailSender>();

Conclusion

Using SendGrid email service, C# nuget package manager and ASP.NET Core MVC web application, we can simply send now an email from the application. Additionally, you can add an attachment with an email and SendGrid email service will send it by attaching in the email body as well!

Cheers!

History

  • 8th October, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

RM Shahidul Islam Shahed
Program Manager
Bangladesh Bangladesh
PM, CSM®, CSD®

Comments and Discussions

 
GeneralMy vote of 5 Pin
Аslam Iqbal8-Oct-19 6:06
professionalАslam Iqbal8-Oct-19 6:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 8 Oct 2019

Stats

2.7K views
67 downloads
5 bookmarked