How to Send Asp.net Core Email With Sendgrid API

I remember a few months back I wrote a quick post on how I managed to send email using MailKit in one of the projects I was on. Well, as you know there are many different services out there making thing simple to send e-mails from application. Since, I like to test things out first before actually implementing it in a real application, I decided to give Sendgrid a try. Therefore, in this post I will walk you through the steps I took to send emails using the Sendgrid API. Are you ready? Let’s do it!!!

I need to create a brand new application for this post. I am currently using Visual Studio 2019 for this project but feel free to use any other version you may have.

Project Setup

  • First, create a new ASP.NET Core application with the following name “SendgridEmailInAspNetCore”
    “File” –> “New” –> “Project”
    Create new project in Visual Studio 2019
  • A “New Project” dialog will open where you can configure your project such as giving a name and location.
    Configure new project in Visual Studio 2019
  • Make sure the project build properly.
    Now that we have the project setup we need to add the Sendgrid Package using the NuGet Package manager tool.
    Open NuGet free and open-source package manager
    Search and Find the Sendgrid Library in NuGet

Add services folder

  • Let’s add a new folder to the project and called it “Services”. This folder will contain the interface that will be used to send the e-mail.
  • Next we need to add the interface called “IEmailSender.cs”
        using System.Collections.Generic;
        using System.Threading.Tasks;
    
         namespace SendgridEmailInAspNetCore.Services
         {
           public interface IEmailSender
           {
              Task SendEmailAsync(List emails, string subject, string message);
           }
         }
    
    
  • Add an Implementation class called “EmailSender.cs.
    using Microsoft.Extensions.Options;
    using SendGrid;
    using SendGrid.Helpers.Mail;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    
    namespace SendgridEmailInAspNetCore.Services
    {
        public class EmailSender:IEmailSender
        {
            public EmailSender(IOptions optionsAccessor)
            {
                Options = optionsAccessor.Value;
            }
    
            public EmailAuthOptions Options { get; } //set only via Secret Manager
    
            public Task SendEmailAsync(List emails, string subject, string message)
            {
                // return Execute(Options.SendGridKey, subject, message, email);//to try out later
                return Execute(Environment.GetEnvironmentVariable("SENDEMAILDEMO_ENVIRONMENT_SENDGRID_KEY"), subject, message, emails);
            }
    
            public Task Execute(string apiKey, string subject, string message, List emails)
            {
                var client = new SendGridClient(apiKey);
                var msg = new SendGridMessage()
                {
                    From = new EmailAddress("noreply@domain.com", "Bekenty Jean Baptiste"),
                    Subject = subject,
                    PlainTextContent = message,
                    HtmlContent = message
                };
    
                foreach (var email in emails)
                {
                    msg.AddTo(new EmailAddress(email));
                }
    
                Task response = client.SendEmailAsync(msg);
                return response;
            }
        }
    }
    
  • Next, we’ll add a new class in that same services folder called “EmailAuthOptions.cs” This will only contain the email secrets from sendgrid.

    namespace SendgridEmailInAspNetCore.Services
    {
        public class EmailAuthOptions
        {
            public string SendGridUser { get; set; }
            public string SendGridKey { get; set; }
        }
    }
    

Register the services

  • Find the Startup.cs file, and the ConfigureServices method. Then, add the following two lines.

            services.Configure(Configuration);
            services.AddTransient<IEmailSender, EmailSender>();
    

Setup the Environment Variable

  • Right click on the project and go to the properties. Then, click the debug tab and add a new environment variable with the following key “SENDEMAILDEMO_ENVIRONMENT_SENDGRID_KEY”. set the value to what you have gotten from Sendgrid.
    Way to configure sendgrid api key

Build E-mail Interace to capture message from user

  • Let’s add a new model called “EmailModel.cs” with the following properties.
    using System.ComponentModel.DataAnnotations;
    
    namespace SendgridEmailInAspNetCore.Models
    {
        public class EmailModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }
            [Required]
            public string Subject { get; set; }
            [Required]
            public string Message { get; set; }
        }
    }
    
  • Now, let’s add a new view called “SendEmail.cshtml” in the HOME folder with the following content.
          
    @model SendgridEmailInAspNetCore.Models.EmailModel
    
    @{
        ViewData["Title"] = "SendEmail";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Send Email With Sendgrid in Asp.Net Core</h2>
    
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form asp-action="SendEmail">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="Email" class="control-label"></label>
                    <input asp-for="Email" class="form-control" />
                    <span asp-validation-for="Email" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Subject" class="control-label"></label>
                    <input asp-for="Subject" class="form-control" />
                    <span asp-validation-for="Subject" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Message" class="control-label"></label>
                    <textarea asp-for="Message" class="form-control" cols="100"></textarea>
                    <span asp-validation-for="Message" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Send" class="btn btn-default" />
                </div>
            </form>
        </div>
    </div>
    
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
    
           
  • In order to be able to send the email in the controller we’ll need to inject the email service via the constructor so that we can have access to send the emails.
    start the start of the home controller we need to add the follow code snippet.

            private readonly IEmailSender _emailSender;
    
            public HomeController(IEmailSender emailSender)
            {
                _emailSender = emailSender;
            }
    
  • Now, we’re ready to add the email action methods to the controller.
            public IActionResult SendEmail()
            {
                return View();
            }
            public async Task SendEmail(EmailModel model)
            {
                if (ModelState.IsValid)
                {
                    await _emailSender.SendEmailAsync(model.Email, model.Subject, model.Message);
                }
                return View(model);
            }
    

Final Asp.net Core Email With Sendgrid

  • Now that we have everything in place let’s run the application and Test it out.
    Voila, the application loaded with no issues. Let’s navigate to the SendEmail page. Try to send email without entering anything, you should notice the validations.
    Testing the Asp.net Core Email With Sendgrid with empty inputs
  • Now, enter a valid email, subject, and a message, then click the send button.
    Send a valid email with Asp.net Core Email With Sendgrid
  • The moment of truth. Bingo, I got the e-mail in my inbox as shown below.
    Verify that the email was sent
    Verify that the email was received.

51 Business Listing Websites For Local Businesses

If you are a business owner, you should know and understand the importance of having your business listed in the top major search engines on the internet. With the competition being so fierce, those business owners who understand and take action will always win. Therefore, I have compiled a list of all the major platforms for you to list your business and start growing your fan base.

I come up with this list and started using it on some local businesses that I have worked with in the past. Since most of them provide free submission, I thought others would be interest in making use of them to bring more visibility to their business. Getting your business listed on as many online local directories as possible is the best and quickest way to make sure potential new customers find you when searching for products and services related to your business.

Before I start by sharing this list with you. I want you to know that this will not be an easy or quick task. It will require some effort and time on your part to go to each of those website and submit your business information.

Promote on search engines for Local Businesses

Basic checklist to follow when submitting your business those platform

  • NAP – Some of those platforms will on require the basic NAP for your business which is your business’s Name, Address & Phone number. Therefore, make sure that information is the same on all them.
  • Business Description – If you are allowed to submit a business description, take the time to make sure you write something meaningful about the services your business provide. DO NOT LEAVE IT BLANK. This is where you highlight your company’s history and services offered. BE CREATIVE!
  • Website Link – This one of the most important piece of information you MUST provide if your company has a website. This is a great way to drive more traffic to your website and help people who want to learn about your business discover what you have to offer.
  • Pictures And Videos – Majority of listing platforms allow businesses to post pictures and short videos about their services. Take on the opportunity and showcase your business best. Let the world know why they should care about your services or products.
  1. Upamile
  2. Google
  3. Bing
  4. Yelp
  5. Facebook
  6. Better Business Bureau
  7. Angie’s List
  8. Merchant Circle
  9. LinkedIn
  10. YP.com
  11. Whitepages
  12. Superpages.com
  13. Yellowbook
  14. CitySearch
  15. MapQuest/Yext
  16. Local.com
  17. Foursquare
  18. CitySlick
  19. USDirectory.com
  20. BizJournals.com
  21. TeleAtlas
  22. Discover Our Town
  23. EZ Local
  24. CityVoter
  25. Manta
  26. UsCity
  27. InfoUSA
  28. Infignos
  29. Get Fave
  30. My Huckleberry
  31. Yellowee
  32. Brownbook
  33. Magic Yellow
  34. CitySquares
  35. Map Creator
  36. Judy’s Book
  37. TripAdvisor
  38. Thumbtack
  39. YellowPagesGoesGreen.org
  40. Home Advisor
  41. ShowMeLocal
  42. ChamberofCommerce.com
  43. Yellowbot
  44. Hotfrog
  45. Brownbook
  46. InsiderPages
  47. Bizwiki
  48. Business Local Pages
  49. iBegin
  50. Opendi
  51. Sitejabber