SmtpClient with Gmail

后端 未结 6 717
忘了有多久
忘了有多久 2020-11-29 03:47

I\'m developing a mail client for a school project. I have managed to send e-mails using the SmtpClient in C#. This works perfectly with any server but it doesn

6条回答
  •  渐次进展
    2020-11-29 04:34

    I think, you need to validate the server certificate that is used to establish the SSL connections.....

    Use following code to send mail with validating server certificate.....

                this.client = new SmtpClient(_account.SmtpHost, _account.SmtpPort);
                this.client.EnableSsl = _account.SmtpUseSSL;
                this.client.Credentials = new NetworkCredential(_account.Username, _account.Password);
    
            try
            {
                // Create instance of message
                MailMessage message = new MailMessage();
    
                // Add receivers
                for (int i = 0; i < email.Receivers.Count; i++)
                    message.To.Add(email.Receivers[i]);
    
                // Set sender
                message.From = new MailAddress(email.Sender);
    
                // Set subject
                message.Subject = email.Subject;
    
                // Send e-mail in HTML
                message.IsBodyHtml = email.IsBodyHtml;
    
                // Set body of message
                message.Body = email.Message;
    
                //validate the certificate
                ServicePointManager.ServerCertificateValidationCallback =
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                { return true; };
    
    
                // Send the message
                this.client.Send(message);
    
                // Clean up
                message = null;
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not send e-mail. Exception caught: " + e);
            }
    

    Import System.Security.Cryptography.X509Certificates namespace to use ServicePointManager

提交回复
热议问题