This repository was archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 330
How can I send S/MIME emails? #283
Copy link
Copy link
Open
Description
I have a requirement to send an email that's encrypted and signed to a consumer and I'm currently doing it with a third party dependency I'd like to remove. How can I send a encrypted and signed message using this API? I know how to setup an email, assign the mime content and send it, but it seems I'm not formatting the mimecontent correctly...
private static EmailMessage CreateEmailMessage(
ExchangeService emailService,
string senderEmail,
string recipientEmail,
X509Certificate2 encryptCertificate,
X509Certificate2 signCertificate,
object args ) {
byte[] mimeBytes = GetMimeBytes(args, encryptCertificate, signCertificate);
EmailMessage email = new EmailMessage(emailService);
email.ItemClass = "IPM.Note.SMIME";
email.MimeContent = new MimeContent( Encoding.ASCII.HeaderName, mimeBytes );
email.Subject = FormatSubject( args );
email.From = new EmailAddress( senderEmail );
email.ToRecipients.Add( new EmailAddress( recipientEmail ) );
return email;
}
private static byte[] GetMimeBytes( object args, X509Certificate2 encryptCertificate, X509Certificate2 signCertificate ) {
StringBuilder msg = new StringBuilder();
msg.AppendLine( string.Format( "Content-Type: application/pkcs7-mime; smime-type=signed-data;name=smime.p7m" ) );
msg.AppendLine( "Content-Transfer-Encoding: 7bit" );
msg.AppendLine();
msg.AppendLine( args.content );
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, encryptCertificate);
envelope.Encrypt( recipient );
CmsSigner signer = new CmsSigner(signCertificate) {
DigestAlgorithm = new Oid( "sha256" )
};
SignedCms signed = new SignedCms( new ContentInfo(envelope.Encode()) );
signed.ComputeSignature( signer, silent: true );
return signed.Encode();
}
Metadata
Metadata
Assignees
Labels
No labels