I need to send a report through email from my c# console application, but i am getting the below exception when the smtp client send function is called.

System.Net.Mail.SmtpException: 'Failure sending mail.' 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.

Below is the piece of code I use in my application to send an email.

Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword) 
 using (var message = new MailMessage(fromAddress, toAddress)
 {
     Subject = subject,
     Body = body
 })
 {
     smtp.Send(message);
 };

Please help me in finding the issue and send a email.

1

There are 1 best solutions below

0
ChrisFromTheBlock On

I think you missed some code in your post. Your code never shows you using your SMTP.

var fromAddress = new MailAddress("[email protected]", "TestFrom");
var toAddress = new MailAddress("[email protected]", "TestTo");
var host = "smtp.gmail.com";
var port = 587;
var enableSsl = true;
var deliveryMethod = SmtpDeliveryMethod.Network;
var useDefaultCredentials = false;
var credentials = new NetworkCredential(fromAddress.Address, fromPassword)

using (MailMessage message = new MailMessage(fromAddress, toAddress))
{
    message.Subject = "TestSubject";
    message.Body = "TestBody";

    using (SmtpClient mailClient = new SmtpClient(host, port))
    {
        mailClient.EnableSsl = enableSsl;
        mailClient.Credentials = credentials;
        mailClient.Send(message);
    }                               
} 

It should work once you add your mailClient with your host/port. If you're still having problems you can try changing ports to 25 or 465, they are supported by default.