How to Send an Email in .NET Core
This tutorial show you how to send an email in .NET 6.0 using the MailKit email client library.
Install MailKit via NuGet
Visual Studio Package Manager Console: Install-Package MailKit
How to Send an HTML Email in .NET 6.0
This code sends a simple HTML email using the Gmail SMTP service. There are instructions further below on how to use a few other popular SMTP providers - Gmail, Hotmail, Office 365.
// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse("from_address@example.com"));
email.To.Add(MailboxAddress.Parse("to_address@example.com"));
email.Subject = "Email Subject";
email.Body = new TextPart(TextFormat.Html) { Text = "<h1>Test HTML Message Body</h1>" };
// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("[Username]", "[Password]");
smtp.Send(email);
smtp.Disconnect(true);
Send SMTP email with Gmail, Hotmail, Office 365 or AWS SES
To use a different email provider simply update the host parameter passed to the smtp.Connect() method, as shown below example
// gmail
smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
// hotmail
smtp.Connect("smtp.live.com", 587, SecureSocketOptions.StartTls);
// office 365
smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
// aws ses (simple email service)
smtp.Connect("email-smtp.[AWS REGION].amazonaws.com", 587, SecureSocketOptions.StartTls)
To encapsulate the email sending functionality so it's easy to send email from anywhere in your .NET app you can create an EmailService class and IEmailService interface like below.
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
using MimeKit.Text;
namespace EmailExample
{
public interface IEmailService
{
void SendEmail(string to, string subject, string html, string from);
}
public class EmailService : IEmailService
{
public EmailService()
{
}
public void SendEmail(string to, string subject, string html, string from)
{
// create message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(from));
email.To.Add(MailboxAddress.Parse(to));
email.Subject = subject;
email.Body = new TextPart(TextFormat.Html) { Text = html };
// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("username", "password");
smtp.Send(email);
smtp.Disconnect(true);
}
}
}
Comments
Post a Comment