I implemented a simple command line app with C# / NET 6 to act as a filter in E-MailRelay:
using System.IO;
using System.Text;
using MimeKit;
using MimeKit.Cryptography;
namespace E_MailRelay.DKIM.Filter;
/// <summary>
/// Reads an e-mail message, adds a Hardcoded DKIM signature and and writes
the updated message back to disk
/// Note that this requires the installation MailKit to work.
/// </summary>
internal class Program
{
private const string DKIMSelector = "ENTER_YOUR_DKIM_SELECTOR_HERE";
private const string _DKIMDomain = "ENTER_YOUR_DOMAIN_NAME_HERE";
private const string DKIMPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n"
+ @"ENTER_YOUR_PRIVATE_KEY_HERE"
+ "\r\n-----END RSA PRIVATE KEY-----";
private static int Main(string[] args)
{
LoadSignAndRewriteMail(args);
return 102;
}
private static void LoadSignAndRewriteMail(string[] args)
{
var emailMessage = MimeMessage.Load(args[0]);
if (!emailMessage.Headers.Contains(HeaderId.DkimSignature)
&& !emailMessage.Headers.Contains(HeaderId.DomainKeySignature))
{
SignMail(emailMessage);
}
emailMessage.WriteTo(args[0]);
}
private static void SignMail(MimeMessage emailMessage)
{
var pk = DKIMPrivateKey;
MemoryStream stream = new(Encoding.UTF8.GetBytes(pk));
{
stream.Position = 0;
}
var dkimSigner = new DkimSigner(stream, _DKIMDomain, DKIMSelector);
HeaderId[] dkimSignHeaders =
{
HeaderId.To, HeaderId.Cc, HeaderId.Subject, HeaderId.From, HeaderId.Date, HeaderId.MessageId, HeaderId.Body,
HeaderId.Date, HeaderId.MimeVersion, HeaderId.Sender, HeaderId.ReplyTo, HeaderId.ContentTransferEncoding,
HeaderId.ContentId, HeaderId.ContentDescription, HeaderId.ResentDate, HeaderId.ResentFrom,
HeaderId.ResentSender, HeaderId.ResentTo, HeaderId.ResentCc, HeaderId.ResentMessageId, HeaderId.InReplyTo,
HeaderId.References
};
dkimSigner.Sign(FormatOptions.Default, emailMessage, dkimSignHeaders);
}
}