3

I am using mailkit to send a mail in ASP.NET Core Here is my code

var emailMessage = new MimeMessage();

emailMessage.From.Add(new MailboxAddress("Gorrolo", "gorollobikes@gmail.com"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("HTML") { Text = message };

using (var client = new SmtpClient())
{
    client.LocalDomain = "http://localhost:54850";
    await client.ConnectAsync("smtp.gmail.com", 465, false);
    client.Authenticate("Myemail", "Mypassword");
    client.Send(emailMessage);
    //await client.emailMessage(emailMessage).ConfigureAwait(false);
    //await client.DisconnectAsync(true).ConfigureAwait(false);
}

in the line

await client.ConnectAsync("smtp.gmail.com", 465, false)

Debugger sowing the following error The SMTP server has unexpectedly disconnected

wonea
  • 4,783
  • 17
  • 86
  • 139
Gaurav_0093
  • 1,040
  • 6
  • 28
  • 56
  • 2
    You are using the SSL port (465) but you have _useSSL_ = **false**. Try changing that to **true**. If it still fails, keep the **true** and move to port 587 (TLS) – Mad Myche Jun 01 '17 at 11:19
  • 1
    Don't set LocalDomain. It shouldn't be a URL anyway, it's supposed to be a fully qualified domain name. – jstedfast Jun 01 '17 at 20:27

2 Answers2

1

This is what works for me in 2021

void SendGmail(MimeMessage mm)
{
    mm.From.Add(new MailboxAddress("The Email Service", "user@email.com"));
    using SmtpClient client = new(new ProtocolLogger("smtp.log"));
    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
    client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
    client.Authenticate("user@email.com", "My$uperSecr3tPa55w0rd"); // app password
    client.Send(mm);
    client.Disconnect(true);
}
tolsen64
  • 881
  • 1
  • 9
  • 22
0

One of the reasons that this error is received on the 'SmtpClient' while trying to send a message is whenever some of the recipient 'MailboxAddress' (To, Cc, Bcc) is set to an empty string. See details https://github.com/jstedfast/MailKit/issues/866