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

How can I send S/MIME emails? #283

@GanglyCloth

Description

@GanglyCloth

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions