通过VB.NET Windows应用程序发送SendGrid电子邮件的Visual Basic(VB.NET)示例代码

人气:460 发布:2022-10-16 标签: email smtp visual-studio sendgrid

问题描述

我刚刚在我的AWS EC2 Windows服务器2019 My VS 2019 Pro上为我的VB.NET Windows应用程序安装了我的SendGrid帐户。

但我能找到的所有示例都是用C#编写的。

推荐答案

我遇到了与您相同的问题。 我已经开发并测试了C#.NET和VB.NET。 C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using SendGrid;
using SendGrid.Helpers.Mail;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TestSendGrid().Wait();
        }

        static async Task TestSendGrid()
        {
            try
            {
                var apiKey = ConfigurationManager.AppSettings["SENDGRID_APIKEY"];
                var client = new SendGridClient(apiKey);
                var msg = new SendGridMessage()
                {
                    From = new EmailAddress("test@example.com", "Test User"),
                    Subject = "Hello World from the SendGrid C#.NET SDK!",
                    PlainTextContent = "Hello, Email!",
                    HtmlContent = "<strong>Hello, Email!</strong>"
                };
                msg.AddTo(new EmailAddress("test@example.com", "Test User"));
                var response = await client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

VB.NET

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Configuration
Imports SendGrid
Imports SendGrid.Helpers.Mail

Module Module1

    Sub Main()
        TestSendGrid().Wait()
    End Sub

    Private Async Function TestSendGrid() As Task
        Try
            Dim apiKey = ConfigurationManager.AppSettings("SENDGRID_APIKEY")
            Dim client = New SendGridClient(apiKey)
            Dim msg = New SendGridMessage() With {
                .From = New EmailAddress("test@example.com", "Test User"),
                .Subject = "Hello World from the SendGrid VB.NET SDK!",
                .PlainTextContent = "Hello, Email!",
                .HtmlContent = "<strong>Hello, Email!</strong>"
            }
            msg.AddTo(New EmailAddress("test@example.com", "Test User"))
            Dim response = Await client.SendEmailAsync(msg)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Function
End Module

引用:https://docs.microsoft.com/en-us/azure/sendgrid-dotnet-how-to-send-email

376