Sendgrid .NET(對於開發者的運行原理)
SendGrid,作為Twilio SendGrid的一部分,提供雲端服務以協助客戶輕鬆發送電子郵件,簡化溝通流程。 當您建立SendGrid帳戶時,您可使用SMTP中轉與API金鑰等功能,使發送電子郵件訊息變得高效。 SMTP中繼是這一程式的核心,因為它允許您的電子郵件從您的伺服器通過SendGrid的系統發送。 已驗證域名功能可驗證您的域。 由於SendGrid是開源的,您可以存取其GitHub庫並協助修改。
在本指南中,我們旨在解析SendGrid .NET的功能特性,引導您完成初始設置、基本操作及更高階的功能。 無論您是希望通過程式碼發送首次電子郵件,還是優化您的電子郵件行銷活動,本文章都是掌握SendGrid .NET及其與IronPDF的PDF操作整合的起點。
開始使用SendGrid .NET
首先,您需要在您的專案中設置SendGrid .NET。 從安裝SendGrid .NET軟體包開始。 使用NuGet套件管理器來進行此操作。 開啟Visual Studio,然後開啟套件管理器控台。 輸入以下命令:
Install-Package SendGrid

此命令將SendGrid新增到您的專案中。 安裝後,設置您的SendGrid帳戶。 您需要一個API金鑰。 前往SendGrid網站。 如果您還沒有帳戶,請建立一個帳戶。 登入後,導航至設定。 找到API金鑰。 點擊建立API金鑰。 為其命名並選擇存取級別。 複製API金鑰。 您將在您的應用程式中使用這個金鑰。
基本程式碼範例
現在,我們來發送一封電子郵件。 建立一個新的SendGridClient實例。 將您的API金鑰傳遞進構造函式。 然後,建立一個SendGridMessage。 設置發件人和收件人電子郵件地址。 新增主題和電子郵件內容。 最後,使用SendGridClient發送消息。 這是一個基本範例:
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
此程式碼發送一封簡單的電子郵件。 這展示了如何使用SendGrid .NET的基本操作。 您可以從這裡擴展使用更多功能。
實現SendGrid .NET功能
使用自定義HTML內容發送電子郵件
要發送帶有HTML內容的電子郵件,首先建立您的HTML內容。 然後,使用SendGridMessage設置HtmlContent。 這讓您能夠設計豐富的電子郵件。 操作如下:
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
使用SendGrid SMTP服務
有時,您可能更喜歡使用SMTP來發送電子郵件。 SendGrid同樣支持這種方式。 在SendGrid中配置您的SMTP設定。 然後,在您的應用中使用這些設定。 此方法需要設置一個具有SendGrid伺服器資訊的SMTP客戶端。 這是基本設定:
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
管理電子郵件行銷活動
SendGrid .NET允許管理電子郵件行銷活動。 通過API建立、發送和追蹤行銷活動。 有關詳細的行銷活動管理,請參考SendGrid的API文件。 此功能超越基本電子郵件發送,對於行銷活動尤其有價值。
處理退信和垃圾郵件報告
處理退信和垃圾郵件報告至關重要。 SendGrid .NET為這些事件提供了webhook。 在您的SendGrid儀表板中設置webhooks。 然後,在您的應用中處理這些事件。 這有助於保持您的電子郵件列表清潔並提高送達率。
驗證域名
對於電子郵件送達率來說,域名驗證很重要。 它驗證您的域的所有權。在SendGrid中,通過儀表板設置域名驗證。 這涉及到新增DNS記錄。 一旦驗證成功,電子郵件在接收者和電子郵件服務提供者看來會更可信。
整合IronPDF與SendGrid
IronPDF簡介

探索IronPDF功能是一個可以讓開發人員在.NET應用中建立、編輯和擷取PDF內容的程式庫。 它提供了一種以程式化處理PDF文件的簡單方法。 這使得處理PDF文件變得更簡單,無需深入了解PDF規範。 使用IronPDF,開發人員可以使用HTML轉換為PDF,編輯現有PDF,以及提取內容。
Use Case of Merging IronPDF with SendGrid C
在商業應用中,需要動態地生成財務報告、發票或個性化文件,並通過電子郵件發送給客戶或利益相關者。 IronPDF可以用來從模板或資料來源建立這些文件,並轉換為PDF格式。 隨後,使用SendGrid的C#客戶端可以將這些PDF文件附加到電子郵件中,自動發送給預期的收件人。
IronPDF在HTML到PDF轉換方面表現出色,確保精確保留原始佈局和樣式。 它特別適合從基於網頁的內容建立PDF,例如報告、發票和文件。 IronPDF支持HTML文件、URL和原始HTML字串,可輕鬆製作高質量的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");
}
}
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
安裝IronPDF程式庫
要使用IronPDF,您首先需要安裝NuGet包。 首先,打開NuGet套件管理器控台,然後運行此命令:
Install-Package IronPdf
詳細和步驟使用範例程式碼
步驟1:使用IronPDF生成PDF
首先,我們生成一個PDF文件。 我們將從一個HTML字串建立一個簡單的PDF作為範例。
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)
步驟2:設置SendGrid
確保您已安裝SendGrid NuGet包:
Install-Package SendGrid
然後,在您的應用中配置SendGrid。 您將需要來自SendGrid帳戶的API金鑰。
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)
步驟3:建立並發送帶有PDF附件的電子郵件
現在,建立一個電子郵件並附上先前生成的PDF。 最後,通過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
這段程式碼範例展示了生成一個簡單的PDF文件,將其附加到電子郵件中,並通過SendGrid發送。 這是將IronPDF的文件生成和SendGrid的電子郵件功能整合在.NET應用中的直觀過程。
結論

總之,本指南提供了整合SendGrid .NET以提供電子郵件服務和IronPDF以進行PDF文件管理在.NET應用中的全面概覽。 通過遵循列出的步驟,開發者可以高效實現電子郵件發送功能與可自定義HTML內容和SMTP服務選項,以及管理電子郵件行銷活動。
此外,整合IronPDF允許動態生成和發送PDF文件,如財務報告或發票,展示將這些強大的程式庫結合的實際應用範例。 有興趣探索這些功能的開發者可以在投入授權之前利用IronPDF免費試用。 IronPDF授權詳情和定價選項從$999開始。
常見問題
我如何在我的專案中設置SendGrid .NET?
通過Visual Studio中的NuGet Package Manager安裝SendGrid套件來設置SendGrid .NET。安裝後,建立SendGrid帳戶並生成API密鑰以開始發送電子郵件。
使用SendGrid .NET發送電子郵件涉及什麼步驟?
使用您的API密鑰與SendGridClient,構建包含必要發件人和收件人詳細資訊的SendGridMessage,然後使用SendGridClient的SendEmailAsync方法發送郵件。
我如何使用SendGrid .NET發送富含HTML的電子郵件?
要發送富含HTML的電子郵件,請在發送郵件之前將SendGridMessage的HtmlContent屬性設置為您的自定義HTML內容。
在.NET應用中可以使用SMTP與SendGrid嗎?
是的,您可以通過配置SMTP客戶端和SendGrid的SMTP伺服器詳細資訊並使用您的API密鑰作為證書來使用SMTP和SendGrid。
我如何在.NET中生成PDF文件以用於電子郵件附件?
您可以使用IronPDF的ChromePdfRenderer將HTML內容轉換為PDF文件,然後可以使用SaveAs方法將其保存。
如何使用SendGrid將PDF附加到電子郵件?
將PDF轉換為字節陣列、編碼為base64字串,然後使用SendGridMessage的AddAttachment方法將PDF附加到您的電子郵件中。
為什麼在使用SendGrid時域驗證很重要?
域驗證至關重要,因為它驗證了您域的所有權,改善了郵件可傳遞性,並確保您的郵件被收件人視為可信的。
IronPDF如何增強SendGrid在.NET應用中的功能?
IronPDF允許開發人員建立和操作PDF文件,這些文件可以與SendGrid整合以將生成的PDF作為電子郵件附件發送,增強了文件管理能力。
使用SendGrid進行郵件活動管理有何好處?
SendGrid提供強大的功能通過其API建立、發送和跟踪電子郵件活動,提供詳細的管理選項,具體可以參考SendGrid的API文件。
我如何在SendGrid中處理退信和垃圾郵件報告?
使用SendGrid的webhooks來處理退信和垃圾郵件報告。這些webhooks可以通知您的應用關於電子郵件發送問題,使您能夠有效地管理它們。




