Search code examples
c#emailsmtphotmail

Unable to send hotmail from C#


Here is my code:

MailAddress to = new MailAddress("MAIL@hotmail.com");
MailAddress from = new MailAddress("MAIL@hotmail.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "Message du siute as-quebec.net de: " + EmailToSend.Email;
message.Body = EmailToSend.Message;
SmtpClient client = new SmtpClient("smtp.live.com");
client.Credentials = new System.Net.NetworkCredential("MAIL@hotmail.com", "PASSWORD");
client.Send(message);

I have this error:

System.Net.Mail.SmtpException : 'Failure sending mail.'

ExtendedSocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond.

Some ideas what I'm doing wrong?


Solution

  • When using SmtpClient, if one specifies the incorrect value for SMTP server name (ie: SmtpClient.Host), one receives the following error message:

    System.Net.Mail.SmtpException: 'Failure sending mail.'

    WebException: Unable to connect to the remote server

    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


    According to POP, IMAP, and SMTP settings:

    SMTP Settings

    enter image description here


    Also, ensure that you call Dispose for anything that has a Dispose method. The easiest way to do this, is with a using statement (or using declaration).

    Try the following:

    private void SendEmailOutlook(string toAddress, string fromAddress, string subject, string messageText, bool isHtmlMessage, string username, string password)
    {
        MailAddress from = new MailAddress(fromAddress);
    
        using (SmtpClient client = new SmtpClient("smtp.office365.com", 587) { DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = true, UseDefaultCredentials = false })
        {
            client.Credentials = new System.Net.NetworkCredential(username, password);
    
            MailAddress to = new MailAddress(toAddress);
    
            using (MailMessage message = new MailMessage(from, to) { IsBodyHtml = isHtmlMessage })
            {
                message.Subject = subject;
                message.Body = messageText;
    
                client.Send(message);
            }
        }
    }