跳過到頁腳內容
.NET幫助

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 .NET(開發者如何使用):圖1 - 在Visual Studio中通過NuGet程序包管理器控制台安裝SendGrid .NET

此命令將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);
}
$vbLabelText   $csharpLabel

此代碼發送一封簡單的電子郵件。 它展示了使用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);
}
$vbLabelText   $csharpLabel

使用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);
    }
}
$vbLabelText   $csharpLabel

管理電子郵件活動

SendGrid .NET允許管理電子郵件活動。 通過API創建、發送和跟蹤活動。 有關詳細的活動管理,請參考SendGrid的API文檔。 此功能超出基本電子郵件發送,但對於營銷工作非常重要。

處理退信和垃圾郵件報告

處理退信和垃圾郵件報告至關重要。 SendGrid .NET提供這些事件的Webhook。 在您的SendGrid儀表板中設置Webhook。 然後,處理您應用程式中的這些事件。 這可以保持您的電子郵件列表乾淨並提高可傳遞性。

驗證域名

域名驗證對於電子郵件可傳遞性來說很重要。 它驗證您的域的所有權。在SendGrid中,通過儀表板設置域驗證。 這涉及到添加DNS記錄。 驗證後,電子郵件對收件人和電子郵件提供商來說顯得更可靠。

與SendGrid整合IronPDF

Introduction of IronPDF

SendGrid .NET(開發者如何使用):圖2 - IronPDF主頁

探索IronPDF能力是一個允許開發人員在.NET應用程式中創建、編輯和提取PDF內容的程式庫。 它提供了一種直接的方法來以程式方式處理PDF檔案。 它使得處理PDF文件更容易,無需深刻了解PDF規範。 通過IronPDF,開發人員可以使用IronPDF錨點將HTML轉換為PDF、編輯現有PDF並提取內容。

Use Case of Merging IronPDF with SendGrid C#

在一個商業應用程式中,財務報告、賬單或個性化文件需要動態生成,並通過電子郵件發送給客戶或相關者。 IronPDF可以用來從模板或數據源創建這些文件,並將其轉換為PDF格式。 隨後,通過使用SendGrid的C#客戶端,這些PDF文件可以附加到電子郵件中並自動發送給預期的收件人。

IronPDF 在HTML 到 PDF轉換中表現出卓越的能力,確保精確保留原始的版面和風格。 它非常適合從基於網頁的內容(例如報告、發票和文件)創建 PDF。 支持 HTML 文件、URL 和原始 HTML 字串,IronPDF 可以輕鬆生成高品質的 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");
    }
}
$vbLabelText   $csharpLabel

安裝IronPDF程式庫

要使用IronPDF,首先需要安裝NuGet程式包。 首先打開NuGet程序包管理器控制台,然後運行此命令:

Install-Package IronPdf

用例的代碼範例,包含細節和步驟

步驟1:使用IronPDF生成PDF

首先,我們生成一個PDF文件。 我們將創建一個簡單的PDF來自HTML字符串作為範例。

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);
$vbLabelText   $csharpLabel

步驟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);
$vbLabelText   $csharpLabel

步驟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);
}
$vbLabelText   $csharpLabel

此代碼範例說明瞭生成一個簡單的PDF文件、將其附加到電子郵件並通過SendGrid發送。 這是一個直觀的過程,將IronPDF和SendGrid各自在.NET應用程式中的文檔生成和電子郵件功能整合在一起。

結論

SendGrid .NET(開發者如何使用):圖3 - IronPDF授權頁面

總之,本指南提供了有關在.NET應用程式中整合SendGrid .NET進行電子郵件服務和IronPDF進行PDF文件管理的綜合概述。 通過遵循所列步驟,開發人員可以高效地實現帶有可自定義HTML內容和SMTP服務選項的電子郵件發送功能,並管理電子郵件活動。

此外,IronPDF的整合允許動態生成和發送像財務報告或發票這樣的PDF文檔,展示了這些強大程式庫整合的實際用例。 對於有興趣探索這些功能的開發者,在承諾購買授權前可以利用IronPDF免費試用IronPDF 授權詳情及定價選項從$799開始。

常見問題解答

如何在我的項目中設置 SendGrid .NET?

透過 Visual Studio 的 NuGet 套件管理器安裝 SendGrid 套件來設置 SendGrid .NET。安裝後,創建一個 SendGrid 帳戶並生成 API 密鑰以開始發送電子郵件。

使用 SendGrid .NET 發送電子郵件涉及哪些步驟?

使用您的 API 密鑰初始化 SendGridClient,構建包含必要發件人和收件人詳細信息的 SendGridMessage,並通過 SendGridClient 的 SendEmailAsync 方法發送消息。

如何使用 SendGrid .NET 發送帶有豐富 HTML 格式的電子郵件?

要發送 HTML 豐富的電子郵件,在發送電子郵件之前將 SendGridMessage 的 HtmlContent 屬性設定為您的自定義 HTML 內容。

在 .NET 應用程序中,是否可以使用 SendGrid 的 SMTP?

是的,您可以通過將您的 SMTP 客戶端配置為 SendGrid 的 SMTP 伺服器詳細信息並使用您的 API 密鑰作為憑證來使用 SMTP。

如何在 .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 可以通知您的應用關於電子郵件投遞問題,讓您有效地管理它們。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me