Sending S/MIME encrypted email with attachments using C#

0 votes
asked Aug 1, 2012 by Rebex KB (8,210 points)
edited Aug 1, 2012

I'd like to send an S/MIME encrypted email with attachment in .NET.

There is a MSDN forum post about this problem but the code for attachments seems to be rather weird. The code goes for tens and tens lines and does not seem to work. Is there a simpler approach using Rebex Mail?

Applies to: Rebex Secure Mail

1 Answer

0 votes
answered Aug 1, 2012 by Martin Vobr (12,820 points)
edited Aug 1, 2012

Following code will create message, add attachment, encrypt the whole message and send it. Certificate is loaded from the file, but it could be loaded from elsewhere (e.g. from Windows certicate store).

using Rebex.Mail;
using Rebex.Mime.Headers;
using Rebex.Security.Certificates;

// load the certificate 
Certificate recipient = Certificate.LoadDer("joe.cer");
Certificate sender = Certificate.LoadDer("hugo.cer");

// create an instance of MailMessage 
MailMessage message = new MailMessage();

// set its properties to desired values 
message.From = "";
message.To = "";
message.Subject = "This is a simple message";
message.BodyText = "Hello, Joe!";
message.BodyHtml = "Hello, <b>Joe</b>!";

    new Attachment("c:\\")

// Encrypt it using Joe's certificate.
// When using a message.Encrypt(recipient) call, only the reciepient
// will be able to decrypt the message. Following code will
// allow the sender to decrypt it later as well.
message.Encrypt(recipient, sender);

Smtp.Send(message, "");

Further reading