如何通过smtp发送邮件gmail?

How to send mail gmail via smtp?

我在尝试执行此邮件发送方法时收到异常。

{"Syntax error, command unrecognized. The server response was: "}

我的代码:

public async static Task SendExceptionMail(Exception e)
    {
        try
        {
            //TODO: fill..

            var message = new MailMessage();
            message.To.Add("other_email_than_my_email@gmail.com");
            message.From = new MailAddress("my_email_in_gmail@gmail.com");

            message.Subject = "Server Exception Occured";

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Exception occured. Stack trace:");
            sb.AppendLine(e.StackTrace);
            sb.AppendLine("");
            sb.AppendLine("Time: " + DateTime.UtcNow);

            message.Body = sb.ToString();
            message.IsBodyHtml = false;
            message.BodyEncoding = UTF8Encoding.UTF8;

            using (var smtpClient = new SmtpClient())
            {
                smtpClient.Credentials = new System.Net.NetworkCredential("my_email_in_gmail@gmail.com", "very_very_complicated_password_with_numbers_and_signs");
                smtpClient.Host = "smtp.gmail.com";
                smtpClient.Port = 465;
                smtpClient.EnableSsl = true;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                //smtpClient.UseDefaultCredentials = false;
                
                
                await smtpClient.SendMailAsync(message);
            }
        }
        catch (Exception ex)
        {
            Console.Write(ex.StackTrace);
        }
    }

在我的 Gmail 帐户中,我在设置选项卡中允许使用 IMAP 和 POP。

我尝试过的:

我建议你遵循这个 - Sending email in .NET through Gmail and Cannot send mail from certain server

-首先检查 google 帐户设置中是否启用了“Allowing less secure apps to access your account”,然后使用以下代码检查:

using (var smtpClient = new SmtpClient())
            {
                smtpClient.Credentials = new System.Net.NetworkCredential("my_email_in_gmail@gmail.com", "very_very_complicated_password_with_numbers_and_signs");
                smtpClient.Host = "smtp.gmail.com";
                smtpClient.Port = 587; // Google smtp port
                smtpClient.EnableSsl = true;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;// disable it
                /// Now specify the credentials 
smtpClient.Credentials = new NetworkCredential(message.From.Address, fromPassword)

                await smtpClient.SendMailAsync(message);
            }

可能存在一些防火墙问题。

参考文献:
SendEmail in ASP.net shows me Syntax error, command unrecognized. The server response was: Dovecot ready

希望对您有所帮助。