示例#1
0
        static void SendSecurEmail2()
        {
            SecureMailMessage message = new SecureMailMessage();

            // Look up your signing cert by serial number in your cert store
            X509Certificate2 signingCert = CryptoHelper.FindCertificate("1B37D3");
            // Look up your encryption cert the same way
            X509Certificate2 encryptionCert = CryptoHelper.FindCertificate("22C590");

            // Load the recipient's encryption cert from a file.
            X509Certificate2 recipientCert = new X509Certificate2(@"c:\certs\bob.cer");

            message.From = new SecureMailAddress("*****@*****.**", "Alice", encryptionCert, signingCert);
            message.To.Add(new SecureMailAddress("*****@*****.**", "Fred (Bob)", recipientCert));

            message.Subject = "This is a signed and encrypted message";

            message.Body       = "<h2>Sent from the Cpi.Net.SecureMail library!</h2>";
            message.IsBodyHtml = true;

            message.IsSigned    = true;
            message.IsEncrypted = true;

            // Instantiate a good old-fashioned SmtpClient to send your message
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.free.fr", 25);

            // If your SMTP server requires you to authenticate, you need to specify your
            // username and password here.
            //client.Credentials = new NetworkCredential("YourSmtpUserName", "YourSmtpPassword");

            client.Send(message);
        }
        //Send multi mail
        public static bool Send(string[] emailto, string emailfrom, string passwordfrom, string displayname, string title, string body, string[] Attachfile=null)
        {
            try
              {

              // send email  file attached
              SecureMailMessage message = new SecureMailMessage();

              message.From = new SecureMailAddress(emailfrom, displayname);
              //support for sending email to multi users
              foreach (var mail in emailto)
              {
                  try
                  {
                      message.To.Add(new SecureMailAddress(mail, mail));
                  }
                  catch { }
              }
              message.Subject = title;
              message.Body = body;
              message.IsBodyHtml = true;
              //message.IsSigned = true;
              // message.IsEncrypted = false;
              if (Attachfile != null && Attachfile.Length > 0)
              {
                  foreach (var f in Attachfile)
                  {
                      try
                      {
                          SecureAttachment item = new SecureAttachment(f);
                          message.Attachments.Add(item);
                      }
                      catch { }
                  }
              }
              // Instantiate a good old-fashioned SmtpClient to send your message
              System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
              client.EnableSsl = true;

              // If your SMTP server requires you to authenticate, you need to specify your
              // username and password here.
              client.Credentials = new NetworkCredential(emailfrom, passwordfrom);
              ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

              client.Send(message);
              return true;
              }
              catch (Exception ex)
              {
              Console.WriteLine(ex.Message);
              return false;
              }
        }
示例#3
0
        //----------------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        ///    Sends an email signed with a digital signature specified by the X509 certificate file name supplied in the DigitalSignatureFile
        ///    property
        /// </summary>
        /// <param name="toMailAddress"></param>
        /// <param name="toName">Leave blank "" for default</param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="SMTPHost">Leave blank "" for default</param>
        /// <param name="SMTPUsername">Leave blank "" for default</param>
        /// <param name="SMTPPassword">Leave blank "" for default</param>
        /// <param name="fromMailAddress">Leave blank "" for default</param>
        /// <param name="fromName">Leave blank "" for default</param>
        /// <param name="portID">Leave 0 default</param>
        /// <param name="EnableSSL"></param>
        /// <returns>True if the email was sent successfully</returns>
        public static bool SendEmail(
            StringBuilder toMailAddress, StringBuilder toName,
            string subject, string body,
            string SMTPHost, SecureString SMTPUsername, SecureString SMTPPassword,
            SecureString fromMailAddress, SecureString fromName,
            int portID, bool EnableSSL)
        {
            bool isSuccess = true;
            // instantiate here so we can use the finally block to clean up this message ...
            SecureMailMessage message = null;
            X509Certificate2  myCert  = null;

            try {
                //_____0_____ Check the SMTP details ...
                CheckSMTPDetails(ref fromMailAddress, ref fromName, ref SMTPHost, ref SMTPUsername, ref SMTPPassword, ref portID);

                //_____1_____ Lets start the message - note we just want to add the from, to and subject for now
                // If this email is to be signed then we need to keep the body blank ...
                message = new SecureMailMessage();

                // Load the recipient's encryption cert from a file.
                myCert = new X509Certificate2(MGLSecureEmailer.Decrypt(digitalSignatureFile).ToString());

                // Get the digest for this certificate ...
                SetDigest(myCert);

                // Set the from and to user - note that we can add multiple users with this email format
                message.From = new SecureMailAddress(
                    MGLSecureEmailer.Decrypt(fromMailAddress).ToString(),
                    MGLSecureEmailer.Decrypt(fromName).ToString(), null, myCert);

                message.To.Add(new SecureMailAddress(toMailAddress.ToString(), toName.ToString(), null));
                //message.To.Add(new SecureMailAddress("*****@*****.**", "Pak IM Team", null));

                // Add the subject
                message.Subject = subject;

                // Add the body
                message.Body       = body;
                message.IsBodyHtml = bodyIsHTML;

                // We currently ONLY want to SIGN the email, not encrypt it, so set these two values appropriately
                // (and we ALWAYS want to sign it) ...
                message.IsSigned    = true;
                message.IsEncrypted = false;


                //_____2_____ Setup the SMTP client
                System.Net.Mail.SmtpClient smtpClient = new SmtpClient(SMTPHost);

                // The checkSMTPDetails method above has already tried to check if the portID is zero or less
                // So will already be the default value if this is the case, so we can roll right on
                smtpClient = new SmtpClient(SMTPHost, portID);

                // Sort the credentials to be used for the SMTP connection out
                System.Net.NetworkCredential ncAuth = new System.Net.NetworkCredential(
                    MGLSecureEmailer.Decrypt(SMTPUsername).ToString(),
                    MGLSecureEmailer.Decrypt(SMTPPassword).ToString()
                    );

                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials           = ncAuth;

                // To use ssl or not that is the question
                // With the SMTP connection we probably always now want to use SSL or even better, TLS
                if (EnableSSL || SMTPHost.Contains("gmail"))
                {
                    smtpClient.EnableSsl = true;
                }


                //_____3_____ Lets do it!  Send the email - this is neat as the SecureMailMessage can be cast as a MailMessage
                // which is the input that the smtpClient is expecting ...
                smtpClient.Send(message);
            } catch (Exception ex) {
                // Add the exception to the last exception property and ensure that the user knows this Email was not sent by returning false
                isSuccess = false;
                MGLSecureEmailer.LastException = ex;
            } finally {
                //_____4_____ And lastly, lets clean up everything that contains sensitive passwords or private keys
                if (message != null)
                {
                    message.Dispose();
                }

                // and lets also dispose of the certificate information that is being stored in memory ...
                if (myCert != null)
                {
                    myCert = null;
                    DigitalSignatureDigestOID = null;
                }
            }

            return(isSuccess);
        }