Zum Fußzeileninhalt springen
.NET HILFE

Sendgrid .NET (Funktionsweise für Entwickler)

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, making 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:

using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;

// Asynchronous method to send an email using SendGrid
static async Task SendEmailAsync()
{
    // Initialize a SendGrid client with your API key
    var client = new SendGridClient("your_api_key");

    // Create a new email message
    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>"
    };

    // Add a recipient to your email message
    message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));

    // Send the email and retrieve the response
    var response = await client.SendEmailAsync(message);
}
using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;

// Asynchronous method to send an email using SendGrid
static async Task SendEmailAsync()
{
    // Initialize a SendGrid client with your API key
    var client = new SendGridClient("your_api_key");

    // Create a new email message
    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>"
    };

    // Add a recipient to your email message
    message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));

    // Send the email and retrieve the response
    var response = await client.SendEmailAsync(message);
}
Imports SendGrid
Imports SendGrid.Helpers.Mail
Imports System.Threading.Tasks

' Asynchronous method to send an email using SendGrid
Shared Async Function SendEmailAsync() As Task
	' Initialize a SendGrid client with your API key
	Dim client = New SendGridClient("your_api_key")

	' Create a new email message
	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>"
	}

	' Add a recipient to your email message
	message.AddTo(New EmailAddress("recipient_email@example.com", "Recipient Name"))

	' Send the email and retrieve the response
	Dim response = Await client.SendEmailAsync(message)
End Function
$vbLabelText   $csharpLabel

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:

using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;

// Asynchronous method to send an email with custom HTML content
static async Task SendCustomHtmlEmailAsync()
{
    // Initialize a SendGrid client with your API key
    var client = new SendGridClient("your_api_key");

    // Create a new email message with rich HTML content
    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>"
    };

    // Add a recipient to your email message
    message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));

    // Send the email and retrieve the response
    var response = await client.SendEmailAsync(message);
}
using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;

// Asynchronous method to send an email with custom HTML content
static async Task SendCustomHtmlEmailAsync()
{
    // Initialize a SendGrid client with your API key
    var client = new SendGridClient("your_api_key");

    // Create a new email message with rich HTML content
    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>"
    };

    // Add a recipient to your email message
    message.AddTo(new EmailAddress("recipient_email@example.com", "Recipient Name"));

    // Send the email and retrieve the response
    var response = await client.SendEmailAsync(message);
}
Imports SendGrid
Imports SendGrid.Helpers.Mail
Imports System.Threading.Tasks

' Asynchronous method to send an email with custom HTML content
Shared Async Function SendCustomHtmlEmailAsync() As Task
	' Initialize a SendGrid client with your API key
	Dim client = New SendGridClient("your_api_key")

	' Create a new email message with rich HTML content
	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>"
	}

	' Add a recipient to your email message
	message.AddTo(New EmailAddress("recipient_email@example.com", "Recipient Name"))

	' Send the email and retrieve the response
	Dim response = Await client.SendEmailAsync(message)
End Function
$vbLabelText   $csharpLabel

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:

using System.Net;
using System.Net.Mail;

// Method to send an email using SendGrid's SMTP service
void SendSmtpEmail()
{
    // Configure SMTP client with SendGrid's server details
    using (var client = new SmtpClient("smtp.sendgrid.net")
    {
        Port = 587,
        Credentials = new NetworkCredential("apikey", "your_sendgrid_apikey"),
        EnableSsl = true,
    })
    {
        // Create a new mail message
        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,
        };

        // Add a recipient to the mail message
        mailMessage.To.Add("recipient_email@example.com");

        // Send the email
        client.Send(mailMessage);
    }
}
using System.Net;
using System.Net.Mail;

// Method to send an email using SendGrid's SMTP service
void SendSmtpEmail()
{
    // Configure SMTP client with SendGrid's server details
    using (var client = new SmtpClient("smtp.sendgrid.net")
    {
        Port = 587,
        Credentials = new NetworkCredential("apikey", "your_sendgrid_apikey"),
        EnableSsl = true,
    })
    {
        // Create a new mail message
        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,
        };

        // Add a recipient to the mail message
        mailMessage.To.Add("recipient_email@example.com");

        // Send the email
        client.Send(mailMessage);
    }
}
Imports System.Net
Imports System.Net.Mail

' Method to send an email using SendGrid's SMTP service
Private Sub SendSmtpEmail()
	' Configure SMTP client with SendGrid's server details
	Using client = New SmtpClient("smtp.sendgrid.net") With {
		.Port = 587,
		.Credentials = New NetworkCredential("apikey", "your_sendgrid_apikey"),
		.EnableSsl = True
	}
		' Create a new mail message
		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
		}

		' Add a recipient to the mail message
		mailMessage.To.Add("recipient_email@example.com")

		' Send the email
		client.Send(mailMessage)
	End Using
End Sub
$vbLabelText   $csharpLabel

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.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

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;

// Instantiates a new HtmlToPdf object
var Renderer = new HtmlToPdf();

// Constructs a PDF from an HTML string
var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Define the output path for the PDF file
var outputPath = "example.pdf";

// Saves the generated PDF to the specified path
PDF.SaveAs(outputPath);
using IronPdf;

// Instantiates a new HtmlToPdf object
var Renderer = new HtmlToPdf();

// Constructs a PDF from an HTML string
var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Define the output path for the PDF file
var outputPath = "example.pdf";

// Saves the generated PDF to the specified path
PDF.SaveAs(outputPath);
Imports IronPdf

' Instantiates a new HtmlToPdf object
Private Renderer = New HtmlToPdf()

' Constructs a PDF from an HTML string
Private PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

' Define the output path for the PDF file
Private outputPath = "example.pdf"

' Saves the generated PDF to the specified path
PDF.SaveAs(outputPath)
$vbLabelText   $csharpLabel

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;

// Initialize SendGrid client with your API key
var apiKey = "your_sendgrid_api_key";
var client = new SendGridClient(apiKey);
using SendGrid;
using SendGrid.Helpers.Mail;

// Initialize SendGrid client with your API key
var apiKey = "your_sendgrid_api_key";
var client = new SendGridClient(apiKey);
Imports SendGrid
Imports SendGrid.Helpers.Mail

' Initialize SendGrid client with your API key
Private apiKey = "your_sendgrid_api_key"
Private client = New SendGridClient(apiKey)
$vbLabelText   $csharpLabel

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.

using System;
using System.IO;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;

// Asynchronous method to create and send an email with a PDF attachment
async Task SendEmailWithPdfAttachmentAsync()
{
    // Define sender and recipient email addresses
    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>";

    // Create a new email message
    var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

    // Attach the PDF
    var bytes = File.ReadAllBytes("example.pdf");
    var file = Convert.ToBase64String(bytes);
    msg.AddAttachment("example.pdf", file);

    // Send the email and retrieve the response
    var response = await client.SendEmailAsync(msg);
}
using System;
using System.IO;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;

// Asynchronous method to create and send an email with a PDF attachment
async Task SendEmailWithPdfAttachmentAsync()
{
    // Define sender and recipient email addresses
    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>";

    // Create a new email message
    var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

    // Attach the PDF
    var bytes = File.ReadAllBytes("example.pdf");
    var file = Convert.ToBase64String(bytes);
    msg.AddAttachment("example.pdf", file);

    // Send the email and retrieve the response
    var response = await client.SendEmailAsync(msg);
}
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports SendGrid
Imports SendGrid.Helpers.Mail

' Asynchronous method to create and send an email with a PDF attachment
Async Function SendEmailWithPdfAttachmentAsync() As Task
	' Define sender and recipient email addresses
	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>"

	' Create a new email message
	Dim msg = MailHelper.CreateSingleEmail(from, [to], subject, plainTextContent, htmlContent)

	' Attach the PDF
	Dim bytes = File.ReadAllBytes("example.pdf")
	Dim file = Convert.ToBase64String(bytes)
	msg.AddAttachment("example.pdf", file)

	' Send the email and retrieve the response
	Dim response = Await client.SendEmailAsync(msg)
End Function
$vbLabelText   $csharpLabel

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 $799.

Häufig gestellte Fragen

Wie kann ich SendGrid .NET in meinem Projekt einrichten?

Richten Sie SendGrid .NET ein, indem Sie das SendGrid-Paket über den NuGet-Paketmanager in Visual Studio installieren. Nach der Installation erstellen Sie ein SendGrid-Konto und generieren einen API-Schlüssel, um mit dem Senden von E-Mails zu beginnen.

Welche Schritte sind beim Versenden einer E-Mail mit SendGrid .NET erforderlich?

Verwenden Sie den SendGridClient mit Ihrem API-Schlüssel, konstruieren Sie eine SendGridMessage mit den erforderlichen Absender- und Empfängerdaten und senden Sie die Nachricht mit der SendEmailAsync-Methode des SendGridClient.

Wie sende ich HTML-reiche E-Mails mit SendGrid .NET?

Um HTML-reiche E-Mails zu senden, setzen Sie die HtmlContent-Eigenschaft der SendGridMessage auf Ihren benutzerdefinierten HTML-Inhalt, bevor Sie die E-Mail senden.

Ist es möglich, SMTP mit SendGrid in .NET-Anwendungen zu verwenden?

Ja, Sie können SMTP mit SendGrid verwenden, indem Sie Ihren SMTP-Client mit den SMTP-Serverdetails von SendGrid konfigurieren und Ihren API-Schlüssel als Anmeldedaten verwenden.

Wie kann ich ein PDF-Dokument in .NET zur E-Mail-Anlage generation?

Sie können ein PDF-Dokument erstellen, indem Sie IronPDFs ChromePdfRenderer verwenden, um HTML-Inhalt in eine PDF-Datei zu konvertieren, die dann mit der SaveAs-Methode gespeichert werden kann.

Wie ist der Prozess zum Anhängen eines PDFs an eine E-Mail mit SendGrid?

Konvertieren Sie das PDF in ein Byte-Array, kodieren Sie es zu einem Base64-String und verwenden Sie die AddAttachment-Methode von SendGridMessage, um das PDF an Ihre E-Mail anzuhängen.

Warum ist die Domain-Authentifizierung wichtig, wenn Sie SendGrid verwenden?

Die Domain-Authentifizierung ist entscheidend, da sie den Besitz Ihrer Domain verifiziert, die E-Mail-Zustellbarkeit verbessert und sicherstellt, dass Ihre E-Mails von den Empfängern als vertrauenswürdig angesehen werden.

Wie verbessert IronPDF die Funktionalität von SendGrid in .NET-Anwendungen?

IronPDF ermöglicht es Entwicklern, PDF-Dokumente zu erstellen und zu manipulieren, die mit SendGrid integriert werden können, um generierte PDFs als E-Mail-Anhänge zu versenden und so die Dokumentenverwaltung zu verbessern.

Welche Vorteile hat die Verwendung von SendGrid zur Verwaltung von E-Mail-Kampagnen?

SendGrid bietet robuste Funktionen zum Erstellen, Senden und Verfolgen von E-Mail-Kampagnen über seine API und bietet detaillierte Verwaltungsoptionen, wie in der API-Dokumentation von SendGrid beschrieben.

Wie kann ich Bounces und Spam-Berichte in SendGrid behandeln?

Verwenden Sie SendGrids Webhooks, um Bounces und Spam-Berichte zu behandeln. Diese Webhooks können Ihre Anwendung über Zustellprobleme bei E-Mails informieren und Ihnen ermöglichen, diese effektiv zu verwalten.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen