Send encrypted email using S/MIME
Wednesday, January 26th, 2011Sending encrypted and signed S/MIME messages has never been easier:
// C# version
IMail email = Mail
.Html("<html><body>Encrypted and signed</body></html>")
.Subject("Encrypted and signed")
.From(new MailBox("email@in-the-certificate.com", "Alice"))
.To(new MailBox("bob@mail.com", "Bob"))
.AddAttachment(@"c:\report_2010.pdf")
.SignWith(new X509Certificate2("SignCertificate.pfx", ""))
.EncryptWith(new X509Certificate2("EncryptCertificate.pfx", ""))
.EncryptWith(new X509Certificate2("BobsCertificate.pfx", ""))
.Create();
using (Smtp client = new Smtp())
{
client.Connect("smtp.example.com"); // or ConnectSSL
client.UseBestLogin("user", "password");
client.SendMessage(email);
client.Close();
}
' VB.NET version
Dim email As IMail = Mail _
.Html("<html><body>Encrypted and signed</body></html>") _
.Subject("Encrypted and signed") _
.From(New MailBox("email@in-the-certificate.com", "Alice")) _
.To(New MailBox("bob@mail.com", "Bob")) _
.AddAttachment("c:\report_2010.pdf") _
.SignWith(New X509Certificate2("SignCertificate.pfx", "")) _
.EncryptWith(New X509Certificate2("EncryptCertificate.pfx", "")) _
.EncryptWith(New X509Certificate2("BobsCertificate.pfx", "")) _
.Create()
Using client As New Smtp()
client.Connect("smtp.example.com") ' or ConnectSSL
client.UseBestLogin("user", "password")
client.SendMessage(email)
client.Close()
End Using
Remember to encrypt your emails with both sender’s and receiver’s certificates.
This way both parties are able to decrypt such emails.
Common errors you may encounter:
- Please use the PersistKeySet flag when loading from file (new X509Certificate2(_certificatePath, “”, X509KeyStorageFlags.PersistKeySet);) and adding to store
- “Bad key” exception message means that certificate was not for key exchange – makecert needs an extra parameter to create certificate that can be used for symmetric algorithm key exchange: -sky exchange.
- “the enveloped data-message does not contain the specified recipient” means that certificate with the private key is not deployed into the current account/local machine personal store, or not in the certificates list
You can use following commands in VisualStudio Command Prompt to create test certificate:
makecert.exe -pe -r -sv Test_Keys.pvk -n "CN=John Doe,E=email@in-the-certificate.com" -sky exchange Test.cer
pvk2pfx.exe -pvk Test_Keys.pvk -spc Test.cer -pfx Test.pfx

