記錄 SendGrid 如何使用 C# 寄信時,需要留意什麼設定
使用條件
- SendGrid 版本 - Azure Marketplace 內 Twilio SendGrid (非 Azure Service 的 SendGrid Account)
 - 定價層 - 100 封 / 天
 
C# 程式碼
static async Task Main()
        {
            var apiKey = Environment.GetEnvironmentVariable("TWILIO_SendGrid_Key");
            //Check SendGrid Key
            //Console.WriteLine(TWILIO_SendGrid_Key);
            var client = new SendGridClient(apiKey);
            var msg = new SendGridMessage()
            {
                From = new EmailAddress("sender@email.com", "Sender"),
                Subject = "Sending with Twilio SendGrid is Fun",
                PlainTextContent = "and easy to do anywhere, even with C#",
                HtmlContent = "<strong>and easy to do anywhere, even with C#</strong>"
            };
            msg.AddTo(new EmailAddress("recipient@email.com", "Recipient"));
            var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
            //Check HTTP Status Code
            //Console.WriteLine(response.StatusCode);
            //Console.ReadLine();
        }程式碼參考鏈接 - https://github.com/sendgrid/sendgrid-csharp
留意
- 測試時需要安裝 SendGrid 與 SendGrid.Extensions.DependencyInjection 套件, 如使用 Visual Studio 可直接 NuGet 下載;
 - 環境變數加入至使用者的環境變數即可,無法電腦全環境做使用
 - 如寄信失敗, 建議確認 HTTP Status Response 值,測試過程中我發生 Forbidden, 檢查後發現原因為沒有講寄件者加入寄件者驗證內;
 
HTTP Status Forbidden 參考鏈接 - https://stackoverflow.com/questions/61139752/status-forbidden-when-sending-email-with-sendgrid
寄件者驗證
寄件者驗證在 SendGrid 的管理界面下,有針對全域或者單一使用者,我使用的的是 Gmail,故為單一使用者

單擊後將會出現需要輸入資料,切記 Reply 需要可以收信信箱,因為需要驗證帳號

至收信箱驗證,如沒有建議可以至垃圾信件內確認

完成後即可測試
如沒有設定 SPF,信件很大機會被當做垃圾信件,故可考慮進行 SFP 設定。