如何在 C# 中显示来自内联异步事件处理程序的 MailKit 响应

How to Display MailKit Response from an Inline Async Event Handler in C#

我正在用 C# 实现 MailKit 来发送电子邮件。

我需要能够看到服务器的响应。

MessageSent 事件处理程序连接为内联异步方法。

我确信这就是 SmtpClient 的响应始终为空的原因。但是我不明白如何正确提取响应消息。

           var messageToSend = new MimeMessage
            {
                Subject = subject,
                Body = new TextPart(MimeKit.Text.TextFormat.Text) {Text = message_body } 
            };

            foreach (var recipient in recipients)
                messageToSend.To.Add(new MailboxAddress(recipient.Name, recipient.Address));

            var message = "";
            using (var smtp = new MailKit.Net.Smtp.SmtpClient())
            {
                smtp.MessageSent += async (sender, args) =>
                {  // args.Response };
                    smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await smtp.ConnectAsync(Properties.Settings.Default.Email_Host, 587, SecureSocketOptions.StartTls);
                    await smtp.AuthenticateAsync(Properties.Settings.Default.Test_Email_UserName, 
                                                 Properties.Settings.Default.Test_Email_Password);
                    await smtp.SendAsync(messageToSend);
                    await smtp.DisconnectAsync(true);
                   
                    MessageBox.Show(args.Response);// <== doesn't display
                    message =args.Response;// <== this is my second attempt at getting at the response
                };
                 
            }
            MessageBox.Show(message);// <== always display empty string

你需要做的是:

var message = "";
using (var smtp = new MailKit.Net.Smtp.SmtpClient())
{
    smtp.MessageSent += async (sender, args) =>
    {
        message = args.Response
    };

    smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;

    await smtp.ConnectAsync(Properties.Settings.Default.Email_Host, 587, SecureSocketOptions.StartTls);
    await smtp.AuthenticateAsync(Properties.Settings.Default.Test_Email_UserName, 
                                 Properties.Settings.Default.Test_Email_Password);
    await smtp.SendAsync(messageToSend);
    await smtp.DisconnectAsync(true);
}
MessageBox.Show(message);

问题是您的 Connect/Authenticate/Send 逻辑全部在事件回调内部,因此没有留下任何东西来触发事件。