SmimeEncrypt Method |
Namespace: MailBee.Security
Exception | Condition |
---|---|
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic) or encryptionCerts is a null reference or an empty collection. |
MailBeeSmimeWin32Exception | An error occurred and ThrowExceptions is true. |
This method encrypts the specified message using EncryptionAlgorithm and public keys of all the certificates in encryptionCerts collection. If the e-mail message contains multiple recipients, this collection should contain all their certificates. Otherwise, those recipients which have no their certificates listed in encryptionCerts will not be able to decrypt the message on their end.
If you have the encryption certificates as an X509Certificate2Collection object, you can use FromX509Certificate2Collection(X509Certificate2Collection) method to create CertificateCollection object from it.
Thus, to encrypt a message, you need to have public certificates of its recipients. They can be stored in a file, in Windows registry, etc. You can check S/MIME Demo projects shipped with MailBee on how to open certificate stores and find out recipient certificates based on the recipient list of the message (which can be obtained with GetAllRecipients method).
The developer can also use SignAndEncrypt(MailMessage, Certificate, CertificateCollection) method to encrypt a message and sign it with a digital signature in a single method call.
// To use the code below, import these namespaces at the top of your code using System; using MailBee; using MailBee.Mime; using MailBee.Security; // The actual code (put it into a method of your class) // Load the message from file. MailMessage msg = new MailMessage(); msg.LoadMessage(@"C:\Temp\original.eml"); Smime objSmime = new Smime(); try { // Open the system certificate store which contains the recipients certificates. CertificateStore store = new CertificateStore(CertificateStore.OtherPeople, CertStoreType.System, null); // Search the recipient by e-mail. CertificateCollection encryptionCerts = store.FindCertificates("user1@domain.com", CertificateFields.EmailAddress); // Encrypt the message. MailMessage encMsg = objSmime.Encrypt(msg, encryptionCerts); // Save the encrypted message to the disk file. encMsg.SaveMessage(@"C:\Temp\encrypted.eml"); Console.WriteLine("Done."); } catch (MailBeeException ex) { Console.WriteLine(ex.Message); }