Alex Day
Alex Day

Reputation: 39

How to fix 'No connection could be made because the target machine actively refused it' Error when sending email

I'm trying to send a simple test email to check how the mail class works in C#, but when trying to call smtp.send(message); I get the following error: SocketException: No connection could be made because the target machine actively refused it 173.194.207.109:587 I have looked around at the packets in wireshark (although admittedly I don't have the knowledge to make sense of them) and it seems like Google is sending back a [RST, ACK] packet every time I try to send the email. Is there a way to further diagnose this?

var fromAddress = new MailAddress("[email protected]", "FROM NAME");
var toAddress = new MailAddress("[email protected]", "TO NAME");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    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);
}    

Upvotes: 2

Views: 6703

Answers (1)

Jaskier
Jaskier

Reputation: 1095

Looks like you may want to change your port value because you have EnableSsl = true,

Connect to smtp.gmail.com on port 465, if you're using SSL. (Connect on port 587 if you're using TLS.) Sign in with a Google username and password for authentication to connect with SSL or TLS. Reference

Try:

var fromAddress = new MailAddress("[email protected]", "FROM NAME");
var toAddress = new MailAddress("[email protected]", "TO NAME");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 465, //or try: port = 587, or port = 25
    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);
}

This StackOverflow Answer may also be a good reference to use.

Upvotes: 1

Related Questions