1

I tried to write code for sending an email with .NET. This is what I have so far:

MailMessage mail = new MailMessage("mymailaddress@yahoo.com", address);
mail.Subject = subject;
mail.Body = body;
client.Host = "smtp.gmail.com"; 
client.Port = 587;
client.Send(e);

The problem is I get the following exception:

Unhandled Exception: System.Net.Mail.SmtpException: Failure sending mail.

System.Net.WebException: Unable to connect to the remote server.

System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.194.66.109:587

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
aqua
  • 89
  • 1
  • 13

1 Answers1

2

Try this:

using System.Net;
using System.Net.Mail;  

// ...

MailAddress maFrom = new MailAddress("<address>", "<display_name>");
MailAddress maTo = new MailAddress("<address>", "<display_name>");
const string sPassword = "<password>";
const string sSubject = "<subject>";
const string sBody = "<body>";

new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(maFrom.Address, sPassword)
}.Send(new MailMessage(maFrom, maTo) { Subject = sSubject, Body = sBody });
Orion
  • 210
  • 1
  • 5