title: How to encrypt and signed an email in c# with attachment
body: <p>i'm trying to send an email with attachment and need to encrypt it AND sign it.
  I can encrypt it, I can sign it but when i try to do both i get an email signed with unreadable text or an e-mail encrypte with clear text no PJ only the base64string.</p>
  
  <p>thanks for your answer.
  this is my code for better answer :</p>
  
  <pre><code>string message = BuildMessage(body, pjs, false);
  byte[] messageData = Encoding.UTF8.GetBytes(message);
  
  SignedCms signedCms = new SignedCms(new ContentInfo(messageData));
  CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, GetCertificateFromEmailFrom(from));
  signedCms.ComputeSignature(signer);
  
  byte[] signedBytes = signedCms.Encode();
  ContentInfo content = new ContentInfo(signedBytes);
  EnvelopedCms envelopeCms = new EnvelopedCms(content);
  CmsRecipientCollection toRecipientCollection = new CmsRecipientCollection();
  Dictionary&lt;string, X509Certificate2&gt; certificatesForEncryption = new Dictionary&lt;string, X509Certificate2&gt;();
  List&lt;string&gt; mailRefuser = GetCertificateFromEMailTo(to, out certificatesForEncryption);
  foreach (KeyValuePair&lt;string, X509Certificate2&gt; certificate in certificatesForEncryption)
  {
      CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate.Value);
      toRecipientCollection.Add(recipient);
  }
  envelopeCms.Encrypt(toRecipientCollection);
  byte[] encryptedBytes = envelopeCms.Encode();
  
  MailMessage msg = new MailMessage();
  msg.From = new MailAddress(from);
  foreach (string toMail in to)
  {
      msg.To.Add(new MailAddress(toMail));
  }
  msg.Subject = subject;
  
  MemoryStream ms = new MemoryStream(encryptedBytes);
  AlternateView av = new AlternateView(ms, "application/pkcs7-mime; smime-type=enveloped-data"); //"application/pkcs7-mime; smime-type=signed-data;name=smime.p7m; content-transfer-encoding=utf-8; content-disposition=attachment; fileName=smime.p7m;");
  msg.AlternateViews.Add(av);
  
  
  SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["ServerSMTPWithCredentials"]);
  smtpClient.Credentials = new NetworkCredential(login, password);
  ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certifficate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
  smtpClient.EnableSsl = true;
  smtpClient.Send(msg);
  </code></pre>