Skip to content

Instantly share code, notes, and snippets.

@icavalheiro
Created May 14, 2020 21:28
Show Gist options
  • Save icavalheiro/a43511ee5ac3f40aceeb8c18ad9e2e5d to your computer and use it in GitHub Desktop.
Save icavalheiro/a43511ee5ac3f40aceeb8c18ad9e2e5d to your computer and use it in GitHub Desktop.
Email service for donet (and Umbraco) using mailkit
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Text;
using System.Collections.Generic;
namespace Logic.Services
{
public class EmailService
{
public void SendEmail(Dictionary<string, string> to, string message, string replyToEmail, string replyToName, string subject)
{
var email = BuildEmail(to, message, replyToEmail, replyToName, subject);
SendEmail(email);
}
private MimeMessage BuildEmail(Dictionary<string, string> to, string message, string replyToEmail, string replyToName, string subject)
{
var email = new MimeMessage();
foreach (var entry in to)
{
email.To.Add(new MailboxAddress(entry.Key, entry.Value));
}
email.From.Add(new MailboxAddress("this is a great email", "[email protected]"));
email.Subject = subject;
if (replyToEmail != null)
{
email.ReplyTo.Add(new MailboxAddress(replyToName, replyToEmail));
}
email.Body = new TextPart(TextFormat.Html)
{
Text = message
};
return email;
}
private void SendEmail(MimeMessage email)
{
var host = "smtp.sendgrid.net";
var port = 587;
var username = "USER";
var password = "PASS";
using (SmtpClient client = new SmtpClient())
{
client.Connect(host, port, SecureSocketOptions.StartTlsWhenAvailable);
client.Authenticate(username, password);
client.Send(email);
client.Disconnect(true);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment