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

问题描述 投票:0回答:2

我正在用 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
c# email async-await mailkit
2个回答
3
投票

你需要做的是:

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);

问题在于您的连接/身份验证/发送逻辑全部位于事件回调内部,因此没有留下任何内容导致事件被发出。


0
投票

@jstedfast,我们的要求是不要使用await而不是使用下面的代码,这样它就不会等待aynch操作完成。

mailKitSmtpClient.SendAsync(mimeMessage);

但是上面代码的问题是如何处理异常(如果我不使用await)。是否有任何事件给出异常消息或在上述代码处理完成时触发任何事件。

MessageSent 事件仅在消息成功发送到队列时才会触发。如果您能为我们提供无需等待即可运行代码的方法,并且我们可以通过事件跟踪成功/失败/完成状态,这将会很有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.