Writing an encrypted mail via Exchange Web Service

2019-08-02 01:50发布

问题:

I would like to send an encrypted EMail Message with Exchange WEb Services using C#. Is there any possibillity? Thanks
Edit:
My Mail body encrypter:

        public static byte[] encry(string body, ContentTyp typ, string to )
    {
        X509Certificate2 cert = GetMailCertificate(to);
        StringBuilder msg = new StringBuilder();
        msg.AppendLine(string.Format("Content-Type: text/{0}; charset=\"iso-8859-1\"", typ.ToString()));
        msg.AppendLine("Content-Transfer-Encoding: 7bit");
        msg.AppendLine();
        msg.AppendLine(body);
        EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
        CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
        envelope.Encrypt(recipient);
        //System.IO.MemoryStream ms = new System.IO.MemoryStream(envelope.Encode());
        return envelope.Encode();
    }

Main

 byte [] con = encrypted.encry("test", encrypted.ContentTyp.plain, "test@server.com");
        EmailMessage msg1 = new EmailMessage(_server);
        msg1.MimeContent = new MimeContent("UTF-8", con);
        msg1.ToRecipients.Add("user@server.com");

        msg1.InternetMessageHeaders = ??
        msg1.Send();

回答1:

If you are referring to S/Mime encryption, then you'll have to create the encrypted message according to RFC 3852 and RFC 4134. After you've done that, you can send the message.

Using the EWS Managed API, this can be done as follows:

var item = new EmailMessage(service);
item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content);
// Set recipient infos, etc.
item.Send();

EDIT: You should add the standard headers like From, To, Date, Subject, etc. And the content-type.

Subject: Test
From: "sender" <sender@yourcompany.com>
To: "recipient" <recipient@othercompany.com>
Content-Type: application/pkcs7-mime; smime-type=signed-data; name=smime.p7m
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m

Your encrypted body goes here

Just use a StringWriter put all that together. The result is your MIME body.