无法使用 gmail smtp 通过 c# 表单应用程序发送电子邮件

Cant use gmail smtp to send email via c# form app

我在 c# .net 表单应用程序中编写了这段代码来发送电子邮件。代码通过替换 smtp 服务器名称与 yahoo、hotmail、gmx 一起工作,但不与 gmail 一起工作,

            try
            {

                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                var mail = new MailMessage();
                mail.From = new MailAddress(youremail.Text);
                mail.To.Add(txtreceiver.Text);
                mail.Subject = txtsubject.Text;
                mail.IsBodyHtml = true;
                mail.Body = txtbody.Text;
                SmtpServer.Port = 465;
                SmtpServer.UseDefaultCredentials = false;
                SmtpServer.Credentials = new System.Net.NetworkCredential(youremail.Text, yourpass.Text);
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
                MessageBox.Show("Sent sucessfully..!  \n If Email is not found in inbox check junk ");
            }
            catch (Exception s)
            {
                MessageBox.Show("Failled To Send Mail..!");
            }

首先,您必须按照评论中建议的@user1666620 使用端口 587。

然后您还需要允许 "less secure" 设备访问该 GMail 帐户。点击你的账号头像,然后"My Account" -> "Sign-in & Security" -> "Connected Apps & Sites"。在该页面的底部,切换 "Allow less secure apps" 选项。