Hi, Today I'm writing a brief post on how to send mail through SendGrid using C#.
Here I'm using the free mail service offered by SendGrid, which will expire in a month's time.
1) Go to SendGrid and sign up for a free account https://sendgrid.com/
2) Provide the details
Fill in:
- Name, email, password
- Company name (can be anything)
Verify your email address
Add a phone number (sometimes required for verification)
3) Once you are in, go to Settings > API Keys to generate your API Key. Save your api key in a secure place, as it will not be viewable afterwards.
4) Next, you have to create a Sender Authentication. Go to Settings > Sender Authentication and select from the two sender authentication types available.
- Domain Authentication [learn more from SendGrid How-to-set-up-domain-authentication ]
- Single Sender Verification [learn more from SendGrid Docs sender-verification ]
Below is my C# code for a very basic POC console application
public static void SendEmail()
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
MailMessage mail = new MailMessage("from@mail.com", "to@mail.com");
mail.Subject = "3rd mail TEST Personal Email";
mail.Body = "3rd mail TEST Personal Sent using manual SMTP ";
using (SmtpClient smtp = new SmtpClient("smtp.sendgrid.net", 587))
{
smtp.Credentials = new NetworkCredential("apikey", "SG.h2******.*******-***");
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
}
}
Note: SG.h2******.*******-*** is the API Key I received from SendGrid
Execute the code and get your mails delivered. You can also view the mail delivery status from SendGrid Activity Feed.