Monday, 22 October 2018

Sending Emails using SendGrid in C#.net



1. Create an account in SendGrid
2. Create a Console Application and add the following nuget package.
3.Create a email template in SendGrid.




Step:1

Open SendGrid portal> Go to Settings> Click on API Keys



 create API Key






step:2

Create Transactional templates







Code:



namespace Example
{
    using System;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using SendGrid;
    using SendGrid.Helpers.Mail;
    using System.Collections.Generic;
    using System.Net.Mail;

    internal class Example
    {
        private static void Main()
        {
            Execute().Wait();
        }
        static async Task Execute()
        {  

            var client = new SendGridClient("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");   //API ID           
            var msgs = new SendGridMessage()
            {
                From = new EmailAddress("test@test.com", "sivakumar A"),              
                TemplateId = "d-4e3a01ed228d4f6995e9a3659737fea0"      //Templated ID                    
            };
            var dynamicTemplateData = new TemplateData
            {
                address = "Chennai",
                name = "Ilink",
                sub="Welcome"
                
            };
            msgs.SetTemplateData(dynamicTemplateData);        
            msgs.AddTo(new EmailAddress("test@test.com", "Sivakumar"));
            //Set footer as per your requirement  
            msgs.SetFooterSetting(true, "<strong>Regards,</strong><b> Sivakumar</b>");
            var responses = await client.SendEmailAsync(msgs);
            Console.WriteLine(msgs.Serialize());
            Console.WriteLine(responses.StatusCode);
            Console.WriteLine(responses.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();
        }
    }

    public class TemplateData
    {
        [JsonProperty("address")]
        public string address { get; set; }

        [JsonProperty("name")]
        public string name { get; set; }

        [JsonProperty("sub")]
        public string sub { get; set; }

     
    }
}


output