Search code examples
mailkit

MailKit log is empty on authentication fail


The following code fails after processing AuthenticateAsync() with error:

MailKit.Security.AuthenticationException: 535: Authentication failed.
Restarting authentication process. ---> MailKit.Net.Smtp.SmtpCommandException:
Authentication failed. Restarting authentication process.
public async Task SendMailMessage(M.MailMessage message)
{
  using MemoryStream stream = new MemoryStream(10_240);
  using StreamReader reader = new StreamReader(stream);
  using ProtocolLogger logger = new ProtocolLogger(stream);
  using SmtpClient smtp = new SmtpClient(logger);

  try
  {
    await smtp.ConnectAsync(
      _config.HostName,
      _config.Port,
      _config.SecurityType == EMailSecurityType.StartTls ? SecureSocketOptions.StartTlsWhenAvailable : SecureSocketOptions.Auto
      );
    await smtp.AuthenticateAsync(_config.UserName, _config.Password);
    await smtp.SendAsync(new MimeMessage(message));
    await smtp.DisconnectAsync(true);
  }
  catch
  {
    stream.Flush();
    Debug.Print(reader.ReadToEnd());
  }
}

Why is the log empty?


Solution

  • You need to rewind the stream before reading from it otherwise your position is at the end of the stream when you call ReadToEnd() which will obviously return an empty string.