OfficeDev / ews-managed-api

Other
583 stars 317 forks source link

How can I send S/MIME emails? #283

Open GanglyCloth opened 2 years ago

GanglyCloth commented 2 years ago

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