CURL:

curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header 'Authorization: Bearer <<YOUR_API_KEY>>' \
--header 'Content-Type: application/json' \
--data '{"personalizations":[{"to":[{"email":"john.doe@example.com","name":"John Doe"}],"subject":"Hello, World!"}],"content": [{"type": "text/plain", "value": "Heya!"}],"from":{"email":"sam.smith@example.com","name":"Sam Smith"},"reply_to":{"email":"sam.smith@example.com","name":"Sam Smith"}}'

HTTP POST:

https://api.sendgrid.com/v3/mail/send

Header

Header NameHeader Value
Authorization Bearer <YOUR_API_KEY>

Body

{"personalizations":[{"to":[{"email":"john.doe@example.com","name":"John Doe"}],"subject":"Hello, World!"}],"content": [{"type": "text/plain", "value": "Heya!"}],"from":{"email":"sam.smith@example.com","name":"Sam Smith"}}

Example:

SendGridEmail.cs

   public class SendGridTo
    {
        public string email { get; set; }
        public string name { get; set; }
    }

    public class SendGridPersonalization
    {
        public List<SendGridTo> to { get; set; }
        public string subject { get; set; }
        public SendGridPersonalization()
        {
            this.to = new List<SendGridTo>();
        }
    }

    public class SendGridContent
    {
        public string type { get; set; }
        public string value { get; set; }
    }

    public class SendGridFrom
    {
        public string email { get; set; }
        public string name { get; set; }
    }

    public class SendGridEmail
    {
        public List<SendGridPersonalization> personalizations { get; set; }
        public List<SendGridContent> content { get; set; }
        public SendGridFrom from { get; set; }

        public SendGridEmail()
        {
            this.from = new SendGridFrom { email = "test@test.com", name = "Test" };
            this.personalizations = new List<SendGridPersonalization>();
            this.content = new List<SendGridContent>();
        }
    }
        public async Task TestEmail()
        {
            var message = new SendGridEmail();

            message.content.Add(new SendGridContent { type = "text/html", value = "<b>test is the body</b>" });
            message.personalizations.Add(new SendGridPersonalization { subject = "this is the subject"});
            message.personalizations[0].to.Add(new SendGridTo { email = "test@test.com", name = "test" });

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer xxxxxxxxxxxxxxxxxxxxxxxx);

            var response = await httpClient.PostAsJsonAsync("https://api.sendgrid.com/v3/mail/send", data);

        }

Sources:

https://docs.sendgrid.com/for-developers/sending-email/api-getting-started

Last modified: June 20, 2021

Author

Comments

Write a Reply or Comment