我正在尝试向 textbox1.text 字段中输入的电子邮件地址发送电子邮件。我向 Hotmail 发送电子邮件没有任何问题,但在尝试向 Gmail 发送电子邮件时出现错误。我正在使用此代码发送电子邮件。
string to = Textbox1.Text;
string subject = "Mail subject";
string body = "Hello";
string fromAddress = "[email protected]";
string password = "xyz";
string smtpServer;
int smtpPort;
bool enableSSL;
string domain = to.Substring(to.IndexOf("@") + 1);
switch (domain.ToLower())
{
case "gmail.com":
smtpServer = "smtp.gmail.com";
smtpPort = 587;
enableSSL = true;
break;
case "hotmail.com":
smtpServer = "smtp.office365.com";
smtpPort = 587;
enableSSL = true;
break;
default:
MessageBox.Show("The specified email provider is not supported.");
return;
}
SmtpClient smtpClient = new SmtpClient(smtpServer);
smtpClient.Port = smtpPort;
smtpClient.Credentials = new NetworkCredential(fromAddress, password);
smtpClient.EnableSsl = enableSSL;
MailMessage mailMessage = new MailMessage(fromAddress, to, subject, body);
smtpClient.Send(mailMessage);
下面的文本显示了我在尝试发送电子邮件时遇到的错误。
SMTP 服务器需要安全连接,或者客户端未经过身份验证。服务器响应是:5.7.0 需要身份验证。了解更多信息
像这样更改你的代码;
string to = Textbox1.Text;
string subject = "Mail subject";
string body = "Hello";
string fromAddress = "[email protected]";
string password = "xyz";
string smtpServer;
int smtpPort;
bool enableSSL;
smtpServer = "smtp.office365.com";
smtpPort = 587;
enableSSL = true;
SmtpClient smtpClient = new SmtpClient(smtpServer);
smtpClient.Port = smtpPort;
smtpClient.Credentials = new NetworkCredential(fromAddress, password);
smtpClient.EnableSsl = enableSSL;
MailMessage mailMessage = new MailMessage(fromAddress, to, subject, body);
smtpClient.Send(mailMessage);