Skip to content

Instantly share code, notes, and snippets.

@pichayean
Last active April 27, 2021 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pichayean/2e127d81bc125ecc25a4cc5c61aceb10 to your computer and use it in GitHub Desktop.
Save pichayean/2e127d81bc125ecc25a4cc5c61aceb10 to your computer and use it in GitHub Desktop.
using System;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Text;
namespace email_sender_demo
{
public interface IEmailSenderService
{
void Send(string fromEmail, string toEmail, string subject, string bodyHtml);
}
public class EmailSenderService : IEmailSenderService
{
private readonly string SMTP_USER = Environment.GetEnvironmentVariable("SMTP_USER");
private readonly string SMTP_PASS = Environment.GetEnvironmentVariable("SMTP_PASS");
public void Send(string fromEmail, string toEmail, string subject, string bodyHtml)
{
// create message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(fromEmail));
email.To.Add(MailboxAddress.Parse(toEmail));
email.Subject = subject;
email.Body = new TextPart(TextFormat.Html) { Text = bodyHtml };
// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
smtp.Authenticate(SMTP_USER, SMTP_PASS);
smtp.Send(email);
smtp.Disconnect(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment