This article explains the process of sending an email using SendGrid Email Service with Microsoft Azure. SendGrid is a Cloud based Email Service, which provides reliable transactional Email delivery, scalability and real-time analytics along with flexible APIs, which makes custom integration easy.
This article will cover
- Steps to create a SendGrid account.
- Steps to generate API key for SendGrid account.
- Using SendGrid in an Application to send the Emails.
Creating SendGrid Account
Log in to Azure portal, create a SendGrid resource.
Click New icon.
Search for Sendgrid Email Delivery.
Select SendGrid Email delivery.
Click Create button.
Fields for entering SendGrid account details should appear.
Give a name for your SendGrid account, provide a password for your SendGrid account.
Select the appropriate price tier for your SendGrid account, which is based on your Application usage. For now, let’s create an account with free plan, which can send upto 25000 mail per month.
Provide contact information, which will be used by Azure to communicate SendGrid account related stuff.
Now, read legal terms & click Purchase. Finally, click Create. It will create a SendGrid account for you.
Now, your SendGrid account creates. We need to generate API keys to use it or sending Emails.
Generation of API key
Go to All resources.
Search for “Sendgrid”.
The newly created SendGrid account should appear. Click it.
After selecting the resource group which you have created, click Manage button. This will redirect you to https://app.sendgrid.com
In the left menu, expand settings section, click API Keys under settings.
Click Create API key.
It will ask for API key permission. Choose the appropriate permission.
On Clicking Create & View, a new API key will be generated with the specified permissions.
Using SendGrid to send Emails
- using System;
- using System.IO;
- using System.Net.Mail;
-
- namespace Services
- {
- public class EmailService
- {
- public bool SendEmail(EmailType emailType, object emailDetail)
- {
- var isEmailSent = false;
- try
- {
- var email = new EmailDTO
- {
- Body = "This is email body",
- Subject = "Email Subject",
- IsBodyHtml = true,
- From = "[email protected]",
- To = "[email protected]"
- }
- isEmailSent = SendEmail(email);
- }
- catch (Exception ex)
- {
-
- }
-
- return isEmailSent;
- }
-
- private bool SendEmail(EmailDTO emailDetails)
- {
- try
- {
-
- var apiKey = "dsafags-gsdgsg-5756887547-cnhfgjg";
-
-
-
- var transportWeb = new SendGrid.Web(apiKey);
- var myMessage = new SendGrid.SendGridMessage();
- myMessage.AddTo(emailDetails.To);
- myMessage.From = new MailAddress(emailDetails.From, "HR Driver Referral");
- myMessage.Subject = emailDetails.Subject;
- myMessage.Html = emailDetails.Body;
- transportWeb.DeliverAsync(myMessage);
- return true;
- }
- catch (Exception ex)
- {
-
- return false;
- }
- }
-
- }
- }