0 votes
by (8.4k points)

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
by (13.0k points)

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 = "hugo@example.com";
message.To = "joe@example.com";
message.Subject = "This is a simple message";
message.BodyText = "Hello, Joe!";
message.BodyHtml = "Hello, <b>Joe</b>!";

    new Attachment("c:\\data.zip")

// 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, "smtp.server.com");

Further reading