I wrote the following piece of code for sending an email. First, I wanted to try it with gmail.
Code:
public class EmailSender
{
public static void SendEmail(
string from,
string to,
string smtpaddress, int port,
string username,
string password,
string title,
string body)
{
try
{
SmtpClient client = new SmtpClient(smtpaddress, port);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = title;
mail.Body = body;
mail.IsBodyHtml = true;
client.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Using this is pretty simple:
Code:
class Program
{
public static void Main(string[] args)
{
EmailSender.SendEmail(
"john.doe@gmail.com",
"jane.doe@gmail.com",
"smtp.gmail.com",
465,
"john.doe",
"password",
"test",
"<p>This is a test email!</p>");
}
}
This doesn't work. I get a SmtpException, "The operation has timed out."
I also tried it like this:
Code:
class Program
{
public static void Main(string[] args)
{
EmailSender.SendEmail(
"<john.doe@gmail.com>",
"<jane.doe@gmail.com>",
"smtp.gmail.com",
465,
"john.doe",
"password",
"test",
"<p>This is a test email!</p>");
}
}
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
I am sure that most of the code you posted leaves off the actual username, however, many places require that the username be the e-mail address. Have you tried the full email address as the username?
I am sure that most of the code you posted leaves off the actual username, however, many places require that the username be the e-mail address. Have you tried the full email address as the username?
Some SMTP servers require that the client be authenticated before the server sends e-mail on its behalf. Set this property to true when this SmtpClient object should authenticate using the default credentials of the currently logged on user. If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server.
The thing that is actually strange to me is that the default value is false, in any case, so the way I see it, only this :
Code:
client.Credentials = new System.Net.NetworkCredential(username, password);
Bookmarks