Jump to Section
If you're an IT professional or a developer looking to implement an email notification system in .NET Framework 4.8, SendGrid offers a robust API solution that simplifies this process.
Create the EmailService Class
The EmailService class will be responsible for handling email-sending logic.
Within this class, the Send method will implement the email-sending functionality using the SendGrid.
public class EmailService
{
private static readonly ILogger log = Logger.Create(typeof(EmailService));
private readonly string _appEmailSmtpHost;
private readonly int _appEmailSmtpPort;
private readonly string _appEmailNetworkCredentialUserName;
private readonly string _appEmailNetworkCredentialPassword;
private readonly string _fromEmailAddress;
private readonly string _fromDisplayName;
private SmtpClient _smtpClient = null;
public EmailService(string appEmailSmtpHost,
int appEmailSmtpPort,
string appEmailNetworkCredentialUserName,
string appEmailNetworkCredentialPassword,
string fromEmailAddress,
string fromDisplayName)
{
_appEmailSmtpHost = appEmailSmtpHost;
_appEmailSmtpPort = appEmailSmtpPort;
_appEmailNetworkCredentialPassword = appEmailNetworkCredentialPassword;
_appEmailNetworkCredentialUserName = appEmailNetworkCredentialUserName;
_fromEmailAddress = fromEmailAddress;
_fromDisplayName = fromDisplayName;
}
protected SmtpClient SmtpClient
{
get
{
return _smtpClient ?? (_smtpClient = new SmtpClient(_appEmailSmtpHost, _appEmailSmtpPort)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(_appEmailNetworkCredentialUserName, _appEmailNetworkCredentialPassword),
Timeout = 3 * 60 * 1000 // 180 seconds
});
}
}
public bool Send(string to, string subject, string bodyHtml, string filePath, string replyTo = null)
{
using (var mailMessage = new MailMessage())
{
try
{
mailMessage.IsBodyHtml = true;
mailMessage.From = new MailAddress(_fromEmailAddress, _fromDisplayName);
mailMessage.To.Add(to);
mailMessage.Subject = subject;
mailMessage.Body = $"<html><body>{bodyHtml}</body></html>";
mailMessage.IsBodyHtml = true;
if (!string.IsNullOrWhiteSpace(filePath))
mailMessage.Attachments.Add(new Attachment(filePath));
if (!string.IsNullOrWhiteSpace(replyTo))
{
mailMessage.ReplyToList.Add(new MailAddress(replyTo));
mailMessage.Headers.Add("Reply-To", replyTo);
}
SmtpClient.Send(mailMessage);
}
catch (SmtpException smtpEx)
{
log.Error("SMTP Error sending notification", smtpEx);
return false;
}
catch (Exception ex)
{
log.Error("Error sending notification", ex);
return false;
}
}
return true;
}
}
Here’s a breakdown of the Send method:
Setup Mail Message:
Sets up MailMessage with HTML formatting, "From" address, recipient (to), subject, and HTML body (bodyHtml).
Optional Attachments and Reply-To:
- Adds an attachment if filePath is provided.
- Adds a reply-to address if replyTo is specified.
Send Email:
Uses SmtpClient to send the email.
Error Handling:
Logs SMTP-specific and general errors if email fails to send, returning false on failure and true on success.
Testing the Send Method in Program.cs
Once the EmailService class is set up, you can test the Send method by passing the recipient's email address, subject, and body content.
Here’s an example:
internal class Program
{
static void Main(string[] args)
{
string smtpHost = "smtp.sendgrid.net";
int smtpPort = 587;
string smtpUser = "apikey"; //this is fixed value, leave it
string smtpPassword = "YOUR_SENDGRID_API_KEY"; // such as SG.aDc0s3U3RtG1cNOTDWJnxA.MBswEuYGa...
string fromEmail = "verified@yourdomain.com"; // Must be verified in SendGrid
string fromDisplayName = "Your Company";
var emailService = new EmailService(smtpHost, smtpPort, smtpUser, smtpPassword, fromEmail, fromDisplayName);
// Test email sending
string to = "recipient@example.com";
string subject = "Test Email from Console App";
string bodyHtml = "<p>Please ignore this message.</p>";
string replyTo = "john.rambo.12347@gmail.com";
bool result = emailService.Send(to, subject, bodyHtml, null, replyTo);
Console.ForegroundColor = result ? ConsoleColor.Green : ConsoleColor.Red;
Console.WriteLine(result ? "Email sent successfully." : "Failed to send email.");
Console.ResetColor();
Console.ReadKey();
}
}
Important Considerations
Sender Verification: Make sure the fromEmail address is verified in your SendGrid account to avoid errors like "The from address does not match a verified Sender Identity."
SSL/TLS: SendGrid requires EnableSsl = true for security.
Credentials: The smtpUser field must be set to "apikey", which is a SendGrid requirement when using SMTP with an API key.
Verify Your Sender Identity
Before sending emails, you must verify the Sender Identity.
Sender Identity is the verified email address or domain that an email service provider (like SendGrid) associates with your account and authorizes to send emails on your behalf.
It’s essential because it ensures that only trusted and authorized senders can send emails from your domain, reducing the chances of spam or phishing attacks.
Unverified email addresses will result in an error, commonly this one:
The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements)
in System.Net.Mail.DataStopCommand.CheckResponse(SmtpStatusCode statusCode, String serverResponse)
in System.Net.Mail.DataStopCommand.Send(SmtpConnection conn)
in System.Net.Mail.SmtpConnection.OnClose(Object sender, EventArgs args)
in System.Net.ClosableStream.Close()
in System.Net.Mail.MailWriter.Close()
in System.Net.Mail.SmtpClient.Send(MailMessage message)
Wrapping Up
Following this guide, you can quickly implement email notifications in .NET Framework 4.8 using SendGrid.
This approach allows you to create robust and scalable notification systems for various use cases, from account verifications to support and marketing emails.
What's Next?
Explore our blog for more insights, and feel free to reach out for any queries.