I’m having trouble sending emails through Gmail using C# and keep running into connection issues. Every time I try to connect, I get an error saying the connection was refused by the server.
Here’s what I’m trying to do:
public static void SendEmailMethod()
{
var smtpClient = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("[email protected]", "mypassword"),
EnableSsl = true
};
smtpClient.Send("[email protected]", "[email protected]", "Test Subject", "Test Message");
}
I also tried a different approach with MailMessage:
public static void AlternativeMethod()
{
var senderEmail = new MailAddress("[email protected]", "Sender Name");
var recipientEmail = new MailAddress("[email protected]", "Recipient Name");
const string emailPassword = "mypassword";
const string emailSubject = "Test Email";
const string emailBody = "This is a test message";
var smtpServer = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(senderEmail.Address, emailPassword)
};
using (var emailMessage = new MailMessage(senderEmail, recipientEmail)
{
Subject = emailSubject,
Body = emailBody
})
{
smtpServer.Send(emailMessage);
}
}
Both methods give me the same socket exception error. Has anyone successfully sent emails through Gmail using C#? What am I missing here?