Search code examples
c#smtp

Go Daddy email SMTP not sending email but no error


I've recently purchased the essentials email package from GoDaddy and I am trying to set up sending email from my website via SMTP. I have the following code set up.

var smtp = new SmtpClient
{
    Host = "mycoolwebsite.com.mail.protection.outlook.com",
    Port = 25,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential("info@mycoolwebsite.com", "supersecurepassword")
};
using (var message = new MailMessage("info@mycoolwebsite.com", "myemail@test.com")
{
    IsBodyHtml = true,
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

This gets to send and doesn't throw any exceptions, however the email is not sent. I am very confused at why this doesn't work.

Has anyone got any ideas?


Solution

  • This is going to require TLS which means using MailKit's SMTP. You can get it using the NuGet package manager in Visual Studio. Search for MailKit by Jeffrey Stedfast.

    Documentation is here as well.

    Once you have all the references in place, use the MailKit.Net.Smtp.SmtpClient class:

    • Set "smtp.office365.com" as your host
    • Use port 587.

    You will need to add this line after creating your smtp instance because you have no OAuth token:

    smtp.AuthenticationMechanisms.Remove("XOAUTH2");
    

    That will do what you need.

    Here's an example of what the whole thing should look like:

    string FromPseudonym = "MySite Support";
    string FromAddress = "admin@MySite.com";
    var message = new MimeMessage();
    
    message.From.Add(new MailboxAddress(FromPseudonym, FromAddress));
    message.To.Add(new MailboxAddress("Recipient Pseudonym", "RecipientAddress@somewhere.com"));
    message.Subject = "Testing Email";
    
    var bodyBuilder = new BodyBuilder();
    
    string MsgBody = "Message Body stuff goes here";
    
    bodyBuilder.HtmlBody = MsgBody;
    message.Body = bodyBuilder.ToMessageBody();
    
    using (var client = new SmtpClient())
    {
        client.Connect("smtp.office365.com", 587);
        client.AuthenticationMechanisms.Remove("XOAUTH2");
        client.Authenticate(FromAddress, "Your super secret password goes here");
    
        client.Send(message);
        client.Disconnect(true);
    }
    

    You'll need the following namespaces to be included:

    using MimeKit;
    using MimeKit.Utils;
    using MailKit.Net.Smtp;