Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

How can I send S/MIME emails? #283

Open
GanglyCloth opened this issue Jul 12, 2022 · 0 comments
Open

How can I send S/MIME emails? #283

GanglyCloth opened this issue Jul 12, 2022 · 0 comments

Comments

@GanglyCloth
Copy link

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();
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant