在windows应用程序中使用gmail SMTP服务器发送电子邮件时出现错误

本文关键字:电子邮件 错误 服务器 SMTP 应用程序 windows gmail | 更新日期: 2023-09-27 17:53:06

我试图在c#中编写软件,通过使用gmail帐户在gmail SMTP服务器的帮助下发送电子邮件。它不会产生任何编译错误,但会在运行时抛出异常,即使代码是正确且良好的。

下面是我的代码:
using System.Net;
using System.Net.Mail;
private void button1_Click(object sender, EventArgs e)
{
    if (from.Text != "" && password.Text != "" && to.Text != "" && subject.Text != "" && receive.Text != "")
    {
        try
        {
            MailMessage mail = new MailMessage(from.Text, to.Text, subject.Text, receive.Text);
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            SmtpServer.Port = 465;
            SmtpServer.Credentials = new System.Net.NetworkCredential(from.Text, password.Text);
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);
            MessageBox.Show("Mail Sent");
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.ToString());
            textBox6.Text = ex.ToString();
        }
    }
    else
    { 
        MessageBox.Show("Fill all fields, then press Send button"); 
    }

下面是我得到的例外:

System.Net.Mail。SmtpException: SMTP服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.5.1 Authentication Required。在

了解更多信息在System.Net.Mail.MailCommand

。CheckResponse(SmtpStatusCode, statusCode, String response)
在System.Net.Mail.MailCommand。Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
在System.Net.Mail.SmtpTransport。SendMail(MailAddress发送者,MailAddressCollection接收者,String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException&例外)
在System.Net.Mail.SmtpClient。发送(MailMessage消息)
在Gmail_Sender.Form1。button1_Click(Object sender, EventArgs e) in C:'Users'junaid

在windows应用程序中使用gmail SMTP服务器发送电子邮件时出现错误

GMail不支持465端口的SMTP提交

您需要使用587端口。

也就是说,他们可能不会和你说话,因为他们对IP地址非常挑剔。如果你在一个动态范围内,它可能不会工作,即使你正确设置。

IO。net_io_connectionclosed.

错误信息表明Google不想与您交谈并关闭了连接。