C# SMTP email sending code fails for Yahoo Mail but works fine for other servers, can anyone help?

David Honess picture David Honess · Feb 23, 2011 · Viewed 26k times · Source

I am using this code to send an SMTP email via the yahoo SMTP server, it is for a personal project I am writing.

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

SmtpClient theClient = new SmtpClient("smtp.mail.yahoo.com", 465);
theClient.UseDefaultCredentials = false;
theClient.Credentials = new NetworkCredential("username", "password");
theClient.EnableSsl = true;

MailMessage theMessage = new MailMessage("[email protected]", 
                                         "[email protected]");

theMessage.Subject = "Dave test from C# subject";
theMessage.Body = "Dave test from C# body";

theClient.Send(theMessage);

It's all pretty standard code for sending SMTP email, but... the server seems to throw an error. It forcibly terminates the connection. This does not happen if I use other SMTP servers like Gmail, Windows Live or various other ISP Smtp servers.

This is the exception and stack trace:

System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ConsoleApplication1.Program.Main(String[] args) in E:\dev\ARCSoftware.FTPProcessor\ConsoleApplication1\Program.cs:line 28

I know the problem is not environmental though as I can send to the same server with these exact settings using Outlook Express. I am wondering if I need to send a certificate or something?

If you, or anyone you know where has any ideas about this I would greatly appreciate some help.

Answer

jacobsgriffith picture jacobsgriffith · Sep 26, 2011
using System.Net.Mail;
using System.Net;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btn_Send_Click(object sender, RoutedEventArgs e)
    {
        MailMessage oMail = new MailMessage(new MailAddress("[email protected]"), new MailAddress("[email protected]"));
        SmtpClient oSmtp = new SmtpClient();
        oSmtp.Host = "smtp.mail.yahoo.com";
        oSmtp.Credentials = new NetworkCredential("username", "password");
        oSmtp.EnableSsl = false;
        oSmtp.Port = 587;
        oSmtp.Send(oMail);
    }
}