---
title: "How to send recurring emails in C# .NET using SendGrid and Quartz.NET"
excerpt: "Learn how to send recurring emails with C# .NET using Quartz.NET and SendGrid's APIs"
publishDate: "2022-01-19T00:00:00"
createDate: "2022-01-20T06:42:37.22"
updateDate: "2022-01-20T07:01:15.77"
category: "dotnet"
categoryName: ".NET"
tags: [".NET",".NET 6",".NET Core","SendGrid","Twilio","Email","C#"]
permalink: "/blog/dotnet/how-to-send-recurring-emails-in-csharp-dotnet-using-sendgrid-and-quartzdotnet"
canonical: "https://www.twilio.com/en-us/blog/developers/tutorials/product/how-to-send-recurring-emails-in-csharp-dotnet-using-sendgrid-and-quartz-net"
image: {"crops":[{"alias":"Banner","width":1120,"height":400}],"focalPoint":{"left":0.5,"top":0.5},"src":"/media/mm5k2d34/how-to-send-recurring-emails-in-c-net-using-sendgrid-and-quartz-net-canonical.png"}
imageAlt: "How to send recurring emails in C# .NET using SendGrid and Quartz.NET"
imageBackgroundColor: "#fff"
thumbnailImage: {"crops":[{"alias":"thumbnail","width":250,"height":250}],"focalPoint":{"left":0.5,"top":0.5},"src":"/media/g3cl40tv/sendgrid-logomark.png"}
thumbnailImageAlt: "Twilio SendGrid logo"
metaTitle: "How to send recurring emails in C# .NET using SendGrid and Quartz.NET"
metaDescription: "Learn how to send recurring emails with C# .NET using Quartz.NET and SendGrid's APIs"
ogTitle: "How to send recurring emails in C# .NET using SendGrid and Quartz.NET"
ogDescription: "Learn how to send recurring emails with C# .NET using Quartz.NET and SendGrid's APIs"
ogImage: {"crops":[{"alias":"OpenGraph","width":1200,"height":630}],"focalPoint":{"left":0.5,"top":0.5},"src":"/media/o4kby0eb/how-to-send-recurring-emails-in-c-net-using-sendgrid-and-quartz-net-canonical.png"}
ogImageAlt: "How to send recurring emails in C# .NET using SendGrid and Quartz.NET"
relatedPostKeys: ["5e06985f134049beb903336017f05c40","21cb93b473fc4e32b3cf827e06963462"]
noIndex: false
noFollow: false
sitemapExclude: true
source: {"nodeId":1578,"contentKey":"6aa81681ef174c3584d59f6ae99189e4","sortOrder":119}
---


**This blog post was written for [Twilio](https://www.twilio.com/) and originally published at [the Twilio blog](https://www.twilio.com/blog/how-to-send-recurring-emails-in-csharp-dotnet-using-sendgrid-and-quartz-net).**





Many applications have the need to send emails on a periodic basis. A common example of this is a weekly digest, where the email recaps everything that happened that week. There are many ways you could send recurring emails using .NET. You could use the Task Scheduler on Windows, use crontab on Linux, or even develop your own job scheduling implementation. In this tutorial, you'll learn how to schedule recurring emails using [Twilio SendGrid](https://sendgrid.com/) and [Quartz.NET](https://www.quartz-scheduler.net/).




## Prerequisites {#prerequisites}

You will need the following things to follow along:


-   OS that supports .NET (Windows/Mac/Linux)
-   .NET 6 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/6.0))
-   A code editor or IDE (Recommended: VS Code with C# plugin, Visual Studio, JetBrains Rider)
-   A Twilio SendGrid account ([signup](https://signup.sendgrid.com/))


Everything you’ll need to do for this tutorial applies even if you’re using an older version of .NET (Core), however you’ll need to make minor adjustments.

## Create your .NET application {#create-your-net-application}

You'll be using the .NET worker template because it is the best starting point for this type of application.

Create a new directory and change the current directory to it:

<pre style="color:#000000;background:#ffffff;">mkdir ScheduleMailUsingQuartz&#10;<span style="color:#7f0055; font-weight:bold; ">cd</span> ScheduleMailUsingQuartz&#10;</pre>

Use the .NET CLI to create a new project using the worker template:

<pre style="color:#000000;background:#ffffff;">dotnet new worker&#10;</pre>

Run the new .NET project using the .NET CLI:

<pre style="color:#000000;background:#ffffff;">dotnet run&#10;</pre>

Out of the box, the worker template will continuously run and print a new line to the console every second. The output of the command should look like this:

<pre style="color:#000000;background:#ffffff;">Building...&#10;info: DotNetWorker.Worker[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Worker running at: 01/04/2022 16:31:08 -05:00&#10;info: Microsoft.Hosting.Lifetime[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Application started. Press Ctrl+C to shut down.&#10;info: Microsoft.Hosting.Lifetime[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hosting environment: Development&#10;info: Microsoft.Hosting.Lifetime[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Content root path: /Users/nswimberghe/DotNetWorker&#10;info: DotNetWorker.Worker[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Worker running at: 01/04/2022 16:31:09 -05:00&#10;info: DotNetWorker.Worker[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Worker running at: 01/04/2022 16:31:10 -05:00&#10;info: DotNetWorker.Worker[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Worker running at: 01/04/2022 16:31:11 -05:00&#10;info: DotNetWorker.Worker[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Worker running at: 01/04/2022 16:31:12 -05:00&#10;^Cinfo: Microsoft.Hosting.Lifetime[0]&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Application is shutting down...&#10;</pre>



## Integrate Quartz.NET into worker project {#integrate-quartznet-into-worker-project}



### What is Quartz.NET {#what-is-quartznet}

Quartz.NET is an open source **job scheduler** for .NET. You can use this library to schedule one-off jobs and jobs that should recur on a timed schedule. For this tutorial, you'll run a single instance of Quartz and store the jobs in memory, but you can also run multiple instances of Quartz and store the jobs in a database. Storing the jobs in a database and having multiple instances will help your application become more resilient and process more jobs at a time.

<p class="panel panel--info">There are a lot more features and capabilities that you can learn more about at <a href="https://www.quartz-scheduler.net/">the Quartz.NET website</a>.</p>



### Add Quartz.NET to your project {#add-quartznet-to-your-project}

Use the .NET CLI to add these two Quartz NuGet packages to your project:

<pre style="color:#000000;background:#ffffff;">dotnet add package Quartz&#10;dotnet add package Quartz<span style="color:#7f0055; font-weight:bold; ">.</span>Extensions<span style="color:#7f0055; font-weight:bold; ">.</span>Hosting&#10;</pre>

The [Quartz package](https://www.nuget.org/packages/Quartz/) contains the core capabilities to schedule jobs. The [Quartz.Extensions.Hosting package](https://www.nuget.org/packages/Quartz.Extensions.Hosting/) contains extensions to integrate Quartz with .NET's generic host APIs, which the worker template is already using.

Open up the *ScheduleMailUsingQuartz* directory you created earlier in your preferred text editor and you will see a *Program.cs* file within it. Open up the file and replace the existing code with the following code:

<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; font-weight:bold; ">using</span> Quartz;&#10;&#10;IHost host = Host.CreateDefaultBuilder(args)&#10;    .ConfigureServices((context, services) =&gt;&#10;    {&#10;        services.AddQuartz(q =&gt;&#10;        {&#10;            q.UseMicrosoftDependencyInjectionJobFactory();&#10;            q.ScheduleJob&lt;SendMailJob&gt;(trigger =&gt; trigger&#10;                .WithIdentity(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">SendRecurringMailTrigger</span><span style="color:#2a00ff; ">"</span>)&#10;                .WithSimpleSchedule(s =&gt;&#10;                    s.WithIntervalInSeconds(15)&#10;                    .RepeatForever()&#10;                )&#10;                .WithDescription(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">This trigger will run every 15 seconds to send emails.</span><span style="color:#2a00ff; ">"</span>)&#10;            );&#10;        });&#10;&#10;        services.AddQuartzHostedService(options =&gt;&#10;        {&#10;            <span style="color:#3f7f59; ">// when shutting down we want jobs to complete gracefully</span>&#10;            options.WaitForJobsToComplete = <span style="color:#7f0055; font-weight:bold; ">true</span>;&#10;        });&#10;    })&#10;    .Build();&#10;&#10;await host.RunAsync();&#10;&#10;<span style="color:#7f0055; font-weight:bold; ">class</span> SendMailJob : IJob&#10;{&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> <span style="color:#7f0055; font-weight:bold; ">readonly</span> ILogger logger;&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">public</span> SendMailJob(ILogger&lt;SendMailJob&gt; logger)&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.logger = logger;&#10;    }&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">public</span> async Task Execute(IJobExecutionContext context)&#10;    {&#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Greetings from SendMailJob!</span><span style="color:#2a00ff; ">"</span>);&#10;    }&#10;}&#10;</pre>



<p class="panel panel--info">If you are using older versions of .NET or older templates of .NET, you will need to put the above code and any subsequent code inside the <code>Main</code> method of the <code>Program</code> class. Put any additional classes below the <code>Program</code> class.</p>

With these changes, Quartz is now configured to run the `SendMailJob` every 15 seconds.<br>The `SendMailJob.Execute` method is where you want to add the logic of your job. For now, it logs "Greetings from SendMailJob".

Run the project again and observe the result:

<pre style="color:#000000;background:#ffffff;">dotnet run&#10;</pre>

The output will contain information about Quartz getting up and running. Once Quartz is running, you should see "Greetings from SendMailJob" logged every 15 seconds. The output looks like this:

<pre style="color:#000000;background:#ffffff;">info: Quartz.Core.SchedulerSignalerImpl[0]&#10;      Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImpl&#10;info: Quartz.Core.QuartzScheduler[0]&#10;      Quartz Scheduler created&#10;info: Quartz.Core.QuartzScheduler[0]&#10;      JobFactory set to: Quartz.Simpl.MicrosoftDependencyInjectionJobFactory&#10;info: Quartz.Simpl.RAMJobStore[0]&#10;      RAMJobStore initialized.&#10;info: Quartz.Core.QuartzScheduler[0]&#10;      Scheduler meta-data: Quartz Scheduler (v3.3.3.0) <span style="color:#2a00ff; ">'</span><span style="color:#2a00ff; ">QuartzScheduler</span><span style="color:#2a00ff; ">'</span> with instanceId <span style="color:#2a00ff; ">'</span><span style="color:#2a00ff; ">NON_CLUSTERED</span><span style="color:#2a00ff; ">'</span>&#10;        Scheduler class: <span style="color:#2a00ff; ">'</span><span style="color:#2a00ff; ">Quartz.Core.QuartzScheduler</span><span style="color:#2a00ff; ">'</span> - running locally.&#10;        NOT STARTED.&#10;        Currently in standby mode.&#10;        Number of jobs executed: 0&#10;        Using thread pool <span style="color:#2a00ff; ">'</span><span style="color:#2a00ff; ">Quartz.Simpl.DefaultThreadPool</span><span style="color:#2a00ff; ">'</span> - with 10 threads.&#10;        Using job-store <span style="color:#2a00ff; ">'</span><span style="color:#2a00ff; ">Quartz.Simpl.RAMJobStore</span><span style="color:#2a00ff; ">'</span> - which does not support persistence. and is not clustered.&#10;&#10;info: Quartz.Impl.StdSchedulerFactory[0]&#10;      Quartz scheduler <span style="color:#2a00ff; ">'</span><span style="color:#2a00ff; ">QuartzScheduler</span><span style="color:#2a00ff; ">'</span> initialized&#10;info: Quartz.Impl.StdSchedulerFactory[0]&#10;      Quartz scheduler version: 3.3.3.0&#10;info: Quartz.Core.QuartzScheduler[0]&#10;      Scheduler QuartzScheduler_$_NON_CLUSTERED started.&#10;info: Microsoft.Hosting.Lifetime[0]&#10;      Application started. Press Ctrl+C to shut down.&#10;info: Microsoft.Hosting.Lifetime[0]&#10;      Hosting environment: Development&#10;info: Microsoft.Hosting.Lifetime[0]&#10;      Content root path: /Users/nswimberghe/ScheduleMailUsingQuartz&#10;info: SendMailJob[0]&#10;      Greetings from SendMailJob!&#10;info: SendMailJob[0]&#10;      Greetings from SendMailJob!&#10;info: SendMailJob[0]&#10;      Greetings from SendMailJob!&#10;</pre>

Great job! You've added Quartz to your .NET application and have a job that recurs every 15 seconds.

It doesn't make sense to send an email every 15 seconds, but it makes testing a lot easier! You can use [the simple schedule capabilities](https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/simpletriggers.html) to run the job every X amount of seconds, minutes, or hours. You can also [use CRON expressions](https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/crontriggers.html) to configure longer and more complicated schedules to run your job on.

## Integrate SendGrid to send emails {#integrate-sendgrid-to-send-emails}



### Configuring your SendGrid account to send emails {#configuring-your-sendgrid-account-to-send-emails}

There are two things you need to configure before you can send emails. First, you’ll need to set up Sender Authentication. This will verify that you own the email address or domain that you will send emails from. Second, you’ll need to create a **SendGrid API Key** with permission to send emails.

#### Sender Authentication {#sender-authentication}




It is recommended to configure [**Domain Authentication**](https://docs.sendgrid.com/ui/account-and-settings/how-to-set-up-domain-authentication/) which requires you to add a record to your DNS host. To keep things simple, you will use **Single Sender Verification** instead. This will verify that you own the single email address that you want to send emails from. Single Sender Verification is great for testing purposes, but it is not recommended for production.




<p class="panel panel--warning">Twilio recommends Domain Authentication for production environments. An authenticated domain proves to Inbox Service Providers you own the domain and removes the via sendgrid.net text that inbox providers would otherwise append to your from address.</p>




Go to the SendGrid website and [log in](https://app.sendgrid.com/login). Click on the **Settings** tab in the side menu. Once the settings tab opens up, click on **Sender Authentication**.





![Side-navigation with a Settings group and multiple links in the group. The link "Sender Authentication" is highlighted.](https://twilio-cms-prod.s3.amazonaws.com/images/ZEIFMcC3rj5EX22woLUr7nQrL1-1DDgQ21b8Yy0__it8PV.width-500.png)


Click on **Get Started** under the Single Sender Verification section.


![A button saying "Get Started" to verify an individual email address.](https://twilio-cms-prod.s3.amazonaws.com/images/xGdU3XElcCemrN3DX93RHzT8ZUNmlYYa4OuWBajUB--cxE.width-500.png)


This will open a form on the right-side panel. Fill out the form with your information and email address.


![A form to create a sender. The form asks for contact information including the email address that will be used to send emails from.](https://twilio-cms-prod.s3.amazonaws.com/images/wHvcmoNRQQMoCSdO3xvcPEbfA2LFyfPx9JaFuah-_HzHSy.width-500.png)


Click **Create** after filling out the form. Another panel will appear on the right, asking you to confirm your email address. An email has been sent to the email address you entered.Go to your inbox, open the email from SendGrid, and click Verify Single Sender.


![An email from SendGrid with a button saying "Verify Single Sender".](https://twilio-cms-prod.s3.amazonaws.com/images/AH_xVKGDrRRd_xeXZQaTotdNBelNhdtxwcCIHPncCayCaj.width-500.png)


Your email address has been verified and you can now use it to send emails!

#### Create a SendGrid API key to send emails {#create-a-sendgrid-api-key-to-send-emails}




Back on the SendGrid website, click on **API Keys** under the **Settings tab**. Click on **Create API Key** in the top right corner. This will open another form in the right-side panel. Give your API Key a useful name. You can assign different permissions to the API Key. For optimal security, you should only give the minimum amount of permissions that you need. Click on Restricted Access.





![A form to create an API Key. The form asks for a name for the key and what permissions to grant to the key.](https://twilio-cms-prod.s3.amazonaws.com/images/O79RwuWRbK8pwTuOaR6t56e0mhXVqAQ5izJO85w6kUGB74.width-500.png)


Scroll down to the **Mail Send** accordion item and click on it to reveal the permissions underneath. Drag the slider to the right for the **Mail Send** permission.


![A list of permissions that you can control using a slider bar next to each permission. The "Mail Send" accordion item is expanded to reveal the "Mail Send" permission underneath.](https://twilio-cms-prod.s3.amazonaws.com/images/Fpga88l_rHqmFtN7ROt-cOPlZ1NgrmyRMM3gwDjlmn8LLp.width-500.png)





Scroll to the bottom of the form and click on **Create & View**. The API key will now be displayed on your screen. You will not be able to retrieve the API key again once you leave this screen.





**Copy the secret somewhere safe.**





**![API key is displayed to copy and store elsewhere. Key will not be shown again.](https://twilio-cms-prod.s3.amazonaws.com/images/MMGsdmbcD95aH8tNWepbvT_oXmOSZbikT7LKkQ8acKNtBK.width-500.png)**


With the sender verified and the API Key created, you’re ready to write some code!

### Add Twilio SendGrid to your Quartz.NET job {#add-twilio-sendgrid-to-your-quartznet-job}

Add the following two SendGrid NuGet packages to your project using the .NET CLI:

<pre style="color:#000000;background:#ffffff;">dotnet add package SendGrid&#10;dotnet add package SendGrid<span style="color:#7f0055; font-weight:bold; ">.</span>Extensions<span style="color:#7f0055; font-weight:bold; ">.</span>DependencyInjection&#10;</pre>

The [SendGrid NuGet package](https://www.nuget.org/packages/SendGrid/) will add the core email capabilities. The [SendGrid.Extensions.DependencyInjection NuGet package](https://www.nuget.org/packages/SendGrid.Extensions.DependencyInjection/) adds extensions to add the `ISendGridClient` to the dependency injection container.

Update the *Program.cs* file with the highlighted lines:

<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; font-weight:bold; ">using</span> Quartz;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> SendGrid;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> SendGrid.Extensions.DependencyInjection;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> SendGrid.Helpers.Mail;&#10;&#10;IHost host = Host.CreateDefaultBuilder(args)&#10;    .ConfigureServices((context, services) =&gt;&#10;    {&#10;        services.AddSendGrid(options =&gt;&#10;            options.ApiKey = context.Configuration.GetValue&lt;<span style="color:#7f0055; font-weight:bold; ">string</span>&gt;(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">SendGridApiKey</span><span style="color:#2a00ff; ">"</span>));&#10;&#10;        services.AddQuartz(q =&gt;&#10;        {&#10;            q.UseMicrosoftDependencyInjectionJobFactory();&#10;            q.ScheduleJob&lt;SendMailJob&gt;(trigger =&gt; trigger&#10;                .WithIdentity(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">SendRecurringMailTrigger</span><span style="color:#2a00ff; ">"</span>)&#10;                .WithSimpleSchedule(s =&gt;&#10;                    s.WithIntervalInSeconds(15)&#10;                    .RepeatForever()&#10;                )&#10;                .WithDescription(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">This trigger will run every 15 seconds to send emails.</span><span style="color:#2a00ff; ">"</span>)&#10;            );&#10;        });&#10;&#10;        services.AddQuartzHostedService(options =&gt;&#10;        {&#10;            <span style="color:#3f7f59; ">// when shutting down we want jobs to complete gracefully</span>&#10;            options.WaitForJobsToComplete = <span style="color:#7f0055; font-weight:bold; ">true</span>;&#10;        });&#10;    })&#10;    .Build();&#10;&#10;await host.RunAsync();&#10;&#10;<span style="color:#7f0055; font-weight:bold; ">class</span> SendMailJob : IJob&#10;{&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> <span style="color:#7f0055; font-weight:bold; ">readonly</span> ISendGridClient sendGridClient;&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> <span style="color:#7f0055; font-weight:bold; ">readonly</span> ILogger logger;&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">public</span> SendMailJob(ISendGridClient sendGridClient, ILogger&lt;SendMailJob&gt; logger)&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.sendGridClient = sendGridClient;&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.logger = logger;&#10;    }&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">public</span> async Task Execute(IJobExecutionContext context)&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> msg = <span style="color:#7f0055; font-weight:bold; ">new</span> SendGridMessage()&#10;        {&#10;            From = <span style="color:#7f0055; font-weight:bold; ">new</span> EmailAddress(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">[REPLACE WITH YOUR EMAIL]</span><span style="color:#2a00ff; ">"</span>, <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">[REPLACE WITH YOUR NAME]</span><span style="color:#2a00ff; ">"</span>),&#10;            Subject = <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Sending with Twilio SendGrid is Fun</span><span style="color:#2a00ff; ">"</span>,&#10;            PlainTextContent = <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">and easy to do anywhere, especially with C# .NET</span><span style="color:#2a00ff; ">"</span>&#10;        };&#10;        msg.AddTo(<span style="color:#7f0055; font-weight:bold; ">new</span> EmailAddress(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">[REPLACE WITH DESIRED TO EMAIL]</span><span style="color:#2a00ff; ">"</span>, <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">[REPLACE WITH DESIRED TO NAME]</span><span style="color:#2a00ff; ">"</span>));&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> response = await sendGridClient.SendEmailAsync(msg);&#10;&#10;        <span style="color:#3f7f59; ">// A success status code means SendGrid received the email request and will process it.</span>&#10;        <span style="color:#3f7f59; ">// Errors can still occur when SendGrid tries to send the email. </span>&#10;        <span style="color:#3f7f59; ">// If email is not received, use this URL to debug: </span><span style="color:#3f3fbf; ">https://app.sendgrid.com/email_activity</span><span style="color:#3f7f59; "> </span>&#10;        logger.LogInformation(response.IsSuccessStatusCode ? <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Email queued successfully!</span><span style="color:#2a00ff; ">"</span> : <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Something went wrong!</span><span style="color:#2a00ff; ">"</span>);&#10;    }&#10;}&#10;</pre>




The lambda passed into the `ConfigureServices` method, now receives two parameters: context of type `HostBuilderContext` and services of type `IServiceCollection`. The context parameter has been added because it holds a reference to the configuration that will provide the API key for SendGrid.





`services.AddSendGrid` will add the SendGrid client to the dependency injection container. A lambda is passed into the `AddSendGrid` method to configure the `ApiKey` option. The `SendGridApiKey` is pulled from the configuration and stored into `options.ApiKey`.


Now that SendGrid has been added to the dependency injection container, `ISendGridClient` will be injected into the constructor of `SendMailJob` and stored in a field.

The `Execute` method uses the SendGrid APIs to construct an email and submit it to the SendGrid service.

Update the placeholder strings:


-   replace `[REPLACE WITH YOUR EMAIL]` with the email address you verified with your SendGrid account.
-   replace `[REPLACE WITH YOUR NAME]` with your name.
-   replace `[REPLACE WITH DESIRED TO EMAIL]` with the email address you want to send an email towards.
-   replace `[REPLACE WITH DESIRED TO NAME]` with the recipient's name.


Save the *Program.cs* file.

<p class="panel panel--warning">When the SendGrid API responds with a successful HTTP status code, that does not necessarily mean that the email was successfully received by the recipient. It does however mean that the SendGrid API has accepted your request and will send the email. If the recipient does not receive the email, you can use the <a href="https://app.sendgrid.com/email_activity">Email Activity Feed</a> to find out why.</p>




The project now depends on the <code>SendGridApiKey</code> configuration element, but it hasn't been configured anywhere. You can use .NET user secrets to configure sensitive configuration such as the API key.<strong> </strong>


Add the user secrets NuGet packages using the .NET CLI:

<pre style="color:#000000;background:#ffffff;">dotnet add package Microsoft<span style="color:#7f0055; font-weight:bold; ">.</span>Extensions<span style="color:#7f0055; font-weight:bold; ">.</span>Configuration<span style="color:#7f0055; font-weight:bold; ">.</span>UserSecrets&#10;</pre>

Initialize user secrets for your project using the .NET CLI:

<pre style="color:#000000;background:#ffffff;">dotnet user-secrets init&#10;</pre>



<p class="panel panel--warning">In some cases, user secrets have already been initialized. If that's the case, you will see a warning that your project has already been initialized with a UserSecretsId. You can safely disregard this warning.</p>

Run the following command to set the API key as a user secret:

<pre style="color:#000000;background:#ffffff;">dotnet user-secrets <span style="color:#7f0055; font-weight:bold; ">set</span> SendGridApiKey <span style="color:#2a00ff; ">[</span><span style="color:#2a00ff; ">PASTE IN YOUR SENDGRID API KEY</span><span style="color:#2a00ff; ">]</span>&#10;</pre>

The user secrets configuration will override other configuration sources such as the *appsettings.json* file, but the user secrets will only be loaded when the environment is set as "Development". To do this, you can set an environment variable "DOTNET\_ENVIRONMENT" to "Development". You can also pass it in as a command-line argument like this:

<pre style="color:#000000;background:#ffffff;">dotnet run --environment Development&#10;</pre>

Run the project using the command above. The recurring output should look like this:

<pre style="color:#000000;background:#ffffff;">info: System.Net.Http.HttpClient.InjectableSendGridClient.LogicalHandler[100]&#10;      Start processing HTTP request POST <span style="color:#3f3fbf; ">https://api.sendgrid.com/v3/mail/send</span>&#10;info: System.Net.Http.HttpClient.InjectableSendGridClient.ClientHandler[100]&#10;      Sending HTTP request POST <span style="color:#3f3fbf; ">https://api.sendgrid.com/v3/mail/send</span>&#10;info: System.Net.Http.HttpClient.InjectableSendGridClient.ClientHandler[101]&#10;      Received HTTP response after 15.3421ms - Accepted&#10;info: System.Net.Http.HttpClient.InjectableSendGridClient.LogicalHandler[101]&#10;      End processing HTTP request after 15.4427ms - Accepted&#10;info: SendMailJob[0]&#10;      Email queued successfully!&#10;</pre>

The program should now queue an email every 15 seconds and log "Email queued successfully!". Verify that you are receiving the email by opening your mailbox and look for the email with subject "Sending with Twilio SendGrid is Fun".


![An email with subject "Sending with Twilio SendGrid is Fun" and body "and easy to do anywhere, especially with C# .NET"](https://twilio-cms-prod.s3.amazonaws.com/images/SurTqh31H9QaTrciqeHzJEq_Rtw-9DiHQOOEGz_F51S647.width-500.png)




<p class="panel panel--warning">User secrets are a great way to store secrets and load them into your configuration with .NET. User secrets prevent you from accidentally checking in your secrets to source control by storing the secrets outside your project source. It is important to note that these secrets are still stored in plain text, just elsewhere in your personal folder.</p>



## Conclusion {#conclusion}

Quartz.NET is an open-source job scheduler for .NET. You built a .NET application that sends emails on a recurring schedule by integrating Quartz.NET and the SendGrid API.


Using what you learned here, you can also start integrating SendGrid into your ASP.NET Core applications. Twilio has a lot of other products you can integrate. Check out <a href="https://www.twilio.com/blog/receive-an-sms-and-email-it-using-twilio-sendgrid-c-and-net-core">this tutorial on how to receive text messages using <strong>Twilio Programmable SMS</strong> and forward them using <strong>SendGrid </strong>emails with C# and ASP.NET Core</a>.




## Additional resources {#additional-resources}

Check out the following resources for more information on the topics and tools presented in this tutorial:


<a href="https://www.quartz-scheduler.net/">Quartz.NET website and documentation</a> – You used the minimum amount of code to send emails on a recurring basis using Quartz, but there is a lot more to configure and learn at Quartz' website to get the most out of it. 


[SendGrid .NET SDK source code on GitHub](https://github.com/sendgrid/sendgrid-csharp) – The SendGrid .NET SDK you used in this tutorial is open source! This GitHub repository contains helpful documentation on how to integrate with SendGrid using .NET. You can read the source code to better understand what's happening or submit issues if something isn't working as expected.

[Worker Services in .NET on Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/core/extensions/workers) – Learn more about worker services and how to use it at Microsoft's documentation.

[Source Code to this tutorial on GitHub](https://github.com/Swimburger/ScheduleMailUsingQuartz) - Use this source code if you run into any issues, or submit an issue on this GitHub repo if you run into problems.


<em>Niels Swimberghe is a Belgian software engineer and technical content creator at Twilio, working from the United States. Get in touch with Niels on </em><a href="https://twitter.com/RealSwimburger"><em>Twitter @RealSwimburger</em></a><em> and follow Niels’ personal blog on .NET, Azure, and web development at </em><a href="https://swimburger.net/"><em>swimburger.net</em></a><em>.</em>
