ews-managed-api icon indicating copy to clipboard operation
ews-managed-api copied to clipboard

How can I send S/MIME emails?

Open GanglyCloth opened this issue 3 years ago • 0 comments

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();
}

GanglyCloth avatar Jul 12 '22 21:07 GanglyCloth