I am trying to send an e-mail to the e-mail address entered in the textbox1.text field. I have no problems sending e-mail to Hotmail, but I get an error when trying to send e-mail to Gmail. I'm using this code to send email.
string to = Textbox1.Text;
string subject = "Mail subject";
string body = "Hello";
string fromAddress = "test@hotmail.com";
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);
The text below shows the error I get when trying to send an e-mail.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at
change your code like this;
string to = Textbox1.Text;
string subject = "Mail subject";
string body = "Hello";
string fromAddress = "test@hotmail.com";
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);