.NET HELP

Sendgrid .NET (How It Works For Developers)

Published April 29, 2024
Share:

SendGrid, part of Twilio SendGrid, offers a cloud-based service to help customers send emails simply, streamlining communication processes. When you create a SendGrid account, you gain access to features like SMTP relay and API keys. It makes sending email messages efficient. The SMTP relay is the core of this process as it allows your emails to be sent from your server through SendGrid's system. The authenticated domain feature verifies your domain. As SendGrid is open source, you can access its GitHub repo and help to modify it.

In this guide, we aim to unpack the features and functionalities of SendGrid .NET, guiding you through the initial setup, basic operations, and more advanced features. Whether you’re looking to send your first email through code or optimize your email campaigns, this article is your starting point to mastering SendGrid .NET and its integration with IronPDF for PDF manipulation.

Getting Started with SendGrid .NET

First, you need to set up SendGrid .NET in your project. Start by installing the SendGrid .NET package. Use NuGet Package Manager for this. Open Visual Studio, then open the Package Manager Console. Type the following command:

Install-Package SendGrid

Sendgrid .NET (How It Works For Developers): Figure 1 - Installing SendGrid.NET through NuGet Package Manager Console in Visual Studio

This command adds SendGrid to your project. After installation, set up your SendGrid account. You need an API key. Go to the SendGrid website. Create an account if you don't have one. Once logged in, navigate to Settings. Find API Keys. Click Create API Key. Give it a name and select the access level. Copy the API key. You will use this in your application.

Basic Code Example

Now, let's send an email. Create a new instance of the SendGridClient. Pass your API key to the constructor. Then, create a SendGridMessage. Set the sender and recipient email addresses. Add a subject and the email content. Finally, use SendGridClient to send the message. Here is a basic example:

var client = new SendGridClient("your_api_key");
var message = new SendGridMessage()
{
    From = new EmailAddress("your_email@example.com", "Your Name"),
    Subject = "Hello World from SendGrid",
    PlainTextContent = "This is a test email.",
    HtmlContent = "<strong>This is a test email.</strong>"
};
message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));
var response = await client.SendEmailAsync(message);
var client = new SendGridClient("your_api_key");
var message = new SendGridMessage()
{
    From = new EmailAddress("your_email@example.com", "Your Name"),
    Subject = "Hello World from SendGrid",
    PlainTextContent = "This is a test email.",
    HtmlContent = "<strong>This is a test email.</strong>"
};
message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));
var response = await client.SendEmailAsync(message);
Dim client = New SendGridClient("your_api_key")
Dim message = New SendGridMessage() With {
	.From = New EmailAddress("your_email@example.com", "Your Name"),
	.Subject = "Hello World from SendGrid",
	.PlainTextContent = "This is a test email.",
	.HtmlContent = "<strong>This is a test email.</strong>"
}
message.AddTo(New EmailAddress("recipient_email@example.com", "Recipient Name"))
Dim response = Await client.SendEmailAsync(message)
VB   C#

This code sends a simple email. It shows the basics of using SendGrid .NET. You can expand from here to use more features.

Implement Features of SendGrid .NET

Sending Emails with Custom HTML Content

To send an email with HTML content, you first create your HTML. Then, use SendGridMessage to set HtmlContent. This lets you design rich emails. Here's how:

var client = new SendGridClient("your_api_key");
var message = new SendGridMessage()
{
    From = new EmailAddress("your_email@example.com", "Your Name"),
    Subject = "Custom HTML Content",
    HtmlContent = "<html><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>"
};
message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));
var response = await client.SendEmailAsync(message);
var client = new SendGridClient("your_api_key");
var message = new SendGridMessage()
{
    From = new EmailAddress("your_email@example.com", "Your Name"),
    Subject = "Custom HTML Content",
    HtmlContent = "<html><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>"
};
message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));
var response = await client.SendEmailAsync(message);
Dim client = New SendGridClient("your_api_key")
Dim message = New SendGridMessage() With {
	.From = New EmailAddress("your_email@example.com", "Your Name"),
	.Subject = "Custom HTML Content",
	.HtmlContent = "<html><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>"
}
message.AddTo(New EmailAddress("recipient_email@example.com", "Recipient Name"))
Dim response = Await client.SendEmailAsync(message)
VB   C#

Using SendGrid SMTP Service

Sometimes, you might prefer SMTP to send emails. SendGrid supports this too. Configure your SMTP settings in SendGrid. Then, use these settings in your application. This method requires setting up an SMTP client with SendGrid's server details. Here's a basic setup:

var client = new SmtpClient("smtp.sendgrid.net")
{
    Port = 587,
    Credentials = new NetworkCredential("apikey", "your_sendgrid_apikey"),
    EnableSsl = true,
};
var mailMessage = new MailMessage
{
    From = new MailAddress("your_email@example.com"),
    Subject = "Test SMTP Email",
    Body = "This is a test email sent via SMTP.",
    IsBodyHtml = true,
};
mailMessage.To.Add("recipient_email@example.com");
client.Send(mailMessage);
var client = new SmtpClient("smtp.sendgrid.net")
{
    Port = 587,
    Credentials = new NetworkCredential("apikey", "your_sendgrid_apikey"),
    EnableSsl = true,
};
var mailMessage = new MailMessage
{
    From = new MailAddress("your_email@example.com"),
    Subject = "Test SMTP Email",
    Body = "This is a test email sent via SMTP.",
    IsBodyHtml = true,
};
mailMessage.To.Add("recipient_email@example.com");
client.Send(mailMessage);
Dim client = New SmtpClient("smtp.sendgrid.net") With {
	.Port = 587,
	.Credentials = New NetworkCredential("apikey", "your_sendgrid_apikey"),
	.EnableSsl = True
}
Dim mailMessage As New MailMessage With {
	.From = New MailAddress("your_email@example.com"),
	.Subject = "Test SMTP Email",
	.Body = "This is a test email sent via SMTP.",
	.IsBodyHtml = True
}
mailMessage.To.Add("recipient_email@example.com")
client.Send(mailMessage)
VB   C#

Managing Email Campaigns

SendGrid .NET allows managing email campaigns. Create, send, and track campaigns through the API. For detailed campaign management, refer to SendGrid's API documentation. This feature is beyond basic email sending but is valuable for marketing efforts.

Handling Bounced Emails and Spam Reports

Handling bounces and spam reports is crucial. SendGrid .NET provides webhooks for these events. Set up webhooks in your SendGrid dashboard. Then, process these events in your application. This keeps your email list clean and improves deliverability.

Authenticating Domains

Domain authentication is important for email deliverability. It verifies your domain's ownership. In SendGrid, set up domain authentication via the dashboard. This involves adding DNS records. Once verified, emails appear more trustworthy to recipients and email providers.

Integrate IronPDF with SendGrid

Introduction of IronPDF

Sendgrid .NET (How It Works For Developers): Figure 2 - IronPDF homepage

Explore IronPDF capabilities is a library that allows developers to create, edit, and extract PDF content within .NET applications. It provides a straightforward approach to dealing with PDF files programmatically. It makes it easier to work with PDF files without needing deep knowledge of PDF specifications. With IronPDF, developers can convert HTML to PDF using IronPDF anchors, edit existing PDFs, and extract content.

Use Case of Merging IronPDF with SendGrid C

In a business application, financial reports, invoices, or personalized documents need to be generated dynamically and sent to clients or stakeholders via email. IronPDF can be used to create these documents from templates or data sources, converting them into PDF format. Subsequently, using SendGrid's C# client, these PDF documents can be attached to emails and dispatched automatically to the intended recipients.

Install IronPDF Library

To use IronPDF, you first need to install the NuGet package. First, open the NuGet Package Manager console, then run this command:

Install-Package IronPdf

Code Example of Use Case with Detail and Steps

Step 1: Generate PDF with IronPDF

First, we generate a PDF document. We'll create a simple PDF from an HTML string as an example.

using IronPdf;
var Renderer = new HtmlToPdf();
var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
var outputPath = "example.pdf";
PDF.SaveAs(outputPath);
using IronPdf;
var Renderer = new HtmlToPdf();
var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
var outputPath = "example.pdf";
PDF.SaveAs(outputPath);
Imports IronPdf
Private Renderer = New HtmlToPdf()
Private PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
Private outputPath = "example.pdf"
PDF.SaveAs(outputPath)
VB   C#

Step 2: Set Up SendGrid

Ensure you have the SendGrid NuGet package installed:

Install-Package SendGrid

Then, configure SendGrid in your application. You'll need an API key from your SendGrid account.

using SendGrid;
using SendGrid.Helpers.Mail;
var apiKey = "your_sendgrid_api_key";
var client = new SendGridClient(apiKey);
using SendGrid;
using SendGrid.Helpers.Mail;
var apiKey = "your_sendgrid_api_key";
var client = new SendGridClient(apiKey);
Imports SendGrid
Imports SendGrid.Helpers.Mail
Private apiKey = "your_sendgrid_api_key"
Private client = New SendGridClient(apiKey)
VB   C#

Step 3: Create and Send Email with PDF Attachment

Now, create an email message and attach the previously generated PDF. Finally, send the email through SendGrid.

var from = new EmailAddress("your_email@example.com", "Your Name");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("recipient_email@example.com", "Recipient Name");
var plainTextContent = "Hello, Email!";
var htmlContent = "<strong>Hello, Email!</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
// Attach the PDF
var bytes = File.ReadAllBytes(outputPath);
var file = Convert.ToBase64String(bytes);
msg.AddAttachment("example.pdf", file);
var response = await client.SendEmailAsync(msg);
var from = new EmailAddress("your_email@example.com", "Your Name");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("recipient_email@example.com", "Recipient Name");
var plainTextContent = "Hello, Email!";
var htmlContent = "<strong>Hello, Email!</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
// Attach the PDF
var bytes = File.ReadAllBytes(outputPath);
var file = Convert.ToBase64String(bytes);
msg.AddAttachment("example.pdf", file);
var response = await client.SendEmailAsync(msg);
Dim from = New EmailAddress("your_email@example.com", "Your Name")
Dim subject = "Sending with SendGrid is Fun"
Dim [to] = New EmailAddress("recipient_email@example.com", "Recipient Name")
Dim plainTextContent = "Hello, Email!"
Dim htmlContent = "<strong>Hello, Email!</strong>"
Dim msg = MailHelper.CreateSingleEmail(from, [to], subject, plainTextContent, htmlContent)
' Attach the PDF
Dim bytes = File.ReadAllBytes(outputPath)
Dim file = Convert.ToBase64String(bytes)
msg.AddAttachment("example.pdf", file)
Dim response = Await client.SendEmailAsync(msg)
VB   C#

This code example illustrates generating a simple PDF document, attaching it to an email, and sending it through SendGrid. It's a straightforward process that integrates the document generation and email capabilities of IronPDF and SendGrid, respectively, in a .NET application.

Conclusion

Sendgrid .NET (How It Works For Developers): Figure 3 - IronPDF licensing page

In conclusion, this guide provides a comprehensive overview of integrating SendGrid .NET for email services and IronPDF for PDF document management within .NET applications. By following the outlined steps, developers can efficiently implement email-sending functionalities with customizable HTML content and SMTP service options, and manage email campaigns.

Additionally, the integration of IronPDF allows for the dynamic generation and emailing of PDF documents, such as financial reports or invoices, showcasing a practical use case of merging these powerful libraries. Developers interested in exploring these functionalities can leverage the IronPDF free trial before committing to a license. IronPDF license details and pricing options start from $749.

< PREVIOUS
Tinymce .NET (How It Works For Developers)
NEXT >
C# Devart.Data.Oracle (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >