SMTP gmail в приложении windows - PullRequest
       119

SMTP gmail в приложении windows

0 голосов
/ 24 января 2020

У меня проблема с отправкой электронной почты (gmail), из-за которой я не могу отправить электронное письмо, если у меня не включено «Разрешить менее безопасное приложение». Что я делаю не так?

try

        {

            smtpClient.Host = mServer;
            smtpClient.Port = mPort;
            smtpClient.EnableSsl = isenableSsl;                            

            //Input new time out
            if (mTimeout > 0)
            {
                smtpClient.Timeout = mTimeout;
            }
            //Check Authentication Mode
            if (isAuthentication)
            {
                //Create Network Credentail if SMTP Server Turn On Authentication Mode
                NetworkCredential credentials = new NetworkCredential();
                credentials.UserName = mUserName;
                credentials.Password = mPassword;
                smtpClient.Credentials = credentials;
                smtpClient.UseDefaultCredentials = false;
            }
            else
            {
                smtpClient.UseDefaultCredentials = true;
            }


            //Configuration Mail Information
            if (string.IsNullOrEmpty(mDisplay)) mailMessage.From = new MailAddress(mFrom);
            else mailMessage.From = new MailAddress(mFrom, mDisplay);
            mailMessage.Sender = new MailAddress(mFrom);
            mailMessage.ReplyTo = new MailAddress(mFrom);

            //Set To Email Information
            if (ToEmails.Count != 0)
            {
                mailMessage.To.Clear();
                foreach (string mail in ToEmails)
                {
                    mailMessage.To.Add(mail);
                }
            }

            //Set Cc Email Information
            mailMessage.CC.Clear();
            foreach (string mail in CcEmails)
            {
                mailMessage.CC.Add(mail);
            }
            //Set Bcc Email Information
            mailMessage.Bcc.Clear();
            foreach (string mail in BccEmails)
            {
                mailMessage.Bcc.Add(mail);
            }
            //Set Mail Information
            mailMessage.Subject = mSubject;
            mailMessage.Body = mBody;

            //Configuration Mail Option
            mailMessage.IsBodyHtml = isBodyHtml;
            mailMessage.SubjectEncoding = mSubjectEncoding;
            mailMessage.BodyEncoding = mBodyEncoding;
            mailMessage.Priority = mPriority;
            mailMessage.DeliveryNotificationOptions = mDeliveryNotificationOptions;

            //Clear Attachment File
            mailMessage.Attachments.Clear();

            //Add Attachments Internal File
            AddAttachImage(ref mailMessage);
            //Add Attachments External File
            if (attachmentFiles.Count > 0)
            {
                AddAttachFile(ref mailMessage);
            }
            //Link Event Handler
            smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);

            //Send Message Fuction

            SetLogfileSendEmail(smtpClient, mailMessage);


            ServicePointManager.ServerCertificateValidationCallback =
            delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
            { return true; };

            smtpClient.Send(mailMessage);

        }
        catch (Exception ex)
        {
            strInformation.Append("(Error) Method smtpClient_SendCompleted : " + ex.Message);
            WriteLogFile();
            throw new Exception("SMTP Exception: " + ex.Message);
        }
    }

Это также дает мне

Исключение SMTP: SMTP-сервер требует безопасного соединения или клиент не прошел проверку подлинности. Ответ сервера: 5.7.0 Требуется аутентификация.

Я хочу иметь возможность отправлять электронную почту без необходимости включать опцию «разрешить менее безопасное приложение» в учетной записи gmail.

Есть ли другой способ для сторонних приложений отправлять электронную почту без необходимости «разрешать менее безопасные приложения» ??

1 Ответ

0 голосов
/ 24 января 2020

Если вы (отправитель) используете провайдера Gmail, попробуйте активировать эту опцию

https://www.google.com/settings/security/lesssecureapps

...