Last active
October 18, 2022 12:14
-
-
Save Wanchai/3fc194c8ed19cb84e896b82e6f56548d to your computer and use it in GitHub Desktop.
Sending emails with .Net Core using MailKit with DKIM signature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MailKit.Net.Smtp; | |
using MailKit.Security; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.Logging; | |
using MimeKit; | |
using MimeKit.Cryptography; | |
namespace MailerApi.Services | |
{ | |
public class EmailerService | |
{ | |
private readonly ILogger<EmailerService> Logger; | |
IConfigurationSection SMTP { get; } | |
DkimSigner Signer { get; set; } | |
public EmailerService( | |
IConfiguration config, | |
ILogger<EmailerService> logger | |
) | |
{ | |
Logger = logger; | |
try | |
{ | |
// Used to access appsettings.json | |
SMTP = config.GetSection("smtp"); | |
} | |
catch (System.Exception ex) | |
{ | |
Logger.LogError(ex, ex.Message); | |
} | |
} | |
public void Send(string toName, string toMail, string subject, string body, string bodyHtml) | |
{ | |
try | |
{ | |
Signer = new DkimSigner( | |
"data/dkimkey.txt", // path to your privatekey | |
"mydomain.org", // your domain name | |
"654321.mydomain") // The selector given on https://dkimcore.org/ | |
{ | |
HeaderCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Simple, | |
BodyCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Simple, | |
AgentOrUserIdentifier = "@mydomain.org", // your domain name | |
QueryMethod = "dns/txt", | |
}; | |
// Composing the whole email | |
var message = new MimeMessage(); | |
message.From.Add(new MailboxAddress(SMTP["FromName"], SMTP["From"])); | |
message.To.Add(new MailboxAddress(toName, toMail)); | |
message.Subject = subject; | |
var headers = new HeaderId[] { HeaderId.From, HeaderId.Subject, HeaderId.To }; | |
var builder = new BodyBuilder(); | |
builder.TextBody = body; | |
builder.HtmlBody = bodyHtml; | |
message.Body = builder.ToMessageBody(); | |
message.Prepare(EncodingConstraint.SevenBit); | |
Signer.Sign(message, headers); | |
// Sending the email | |
using(var client = new SmtpClient()) | |
{ | |
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) | |
client.ServerCertificateValidationCallback = (s, c, h, e) => | |
{ | |
Console.WriteLine(e); | |
return true; | |
}; | |
client.Connect(SMTP["Url"], Convert.ToInt32(SMTP["Port"]), SecureSocketOptions.SslOnConnect); | |
client.Authenticate(SMTP["Login"], SMTP["Password"]); | |
client.Send(message); | |
client.Disconnect(true); | |
} | |
} | |
catch (System.Exception ex) | |
{ | |
Logger.LogError(ex, ex.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment