【问题标题】:Using System.Net.Mail to send emails - using the synchronous method 'Send' works, but 'SendAsync' does not使用 System.Net.Mail 发送电子邮件 - 使用同步方法“Send”有效,但“SendAsync”无效
【发布时间】:2021-08-13 15:02:56
【问题描述】:

我正在尝试使用 F# 发送电子邮件,并发现一个代码 sn-p 在使用 Send 时似乎可以工作。我正在使用 gmail 帐户,并确保发件人帐户允许不太安全的应用程序使用它,并且电子邮件和密码组合是正确的。我也在使用端口587SendAsync 似乎不起作用,但它也没有抛出任何看起来很奇怪的异常。

let sendMailMessage email topic msg =
    let msg = new MailMessage(sender, email, topic, msg)
    msg.IsBodyHtml <- false

    let client = new SmtpClient(server, port)
    client.EnableSsl <- true
    client.UseDefaultCredentials <- false
    client.Credentials <- System.Net.NetworkCredential(sender, password)

    client.SendCompleted |> Observable.add(fun e ->
        let msg = e.UserState :?> MailMessage
        if e.Cancelled then
            ("Mail message cancelled:\r\n" + msg.Subject) |> Console.WriteLine
        if e.Error <> null then
            ("Sending mail failed for message:\r\n" + msg.Subject + ", reason:\r\n" + e.Error.ToString()) |> Console.WriteLine
        if msg <> Unchecked.defaultof<MailMessage> then
            msg.Dispose()
        if client<>Unchecked.defaultof<SmtpClient> then
            client.Dispose()
    )

    try
        client.SendAsync(msg, msg) // runs fine but doesn't actually send an email
        client.Send(msg) // this works, but it's also blocking
    with
    | e -> printfn "%A" e

我想知道我是否做错了什么。我目前正在一个测试项目中直接从 main 调用该函数。

【问题讨论】:

    标签: asynchronous f# smtp


    【解决方案1】:

    听起来您的程序可能在SendAsync 完成之前退出。作为一个测试,尝试在main 的末尾加上一个Console.ReadLine 以防止过早退出。

    【讨论】:

    • 你是对的,这就是问题所在。在测试异步函数时,我应该牢记这一点。
    【解决方案2】:

    由于client.SendAsync(msg, msg) 返回一个Task,当您处于同步函数中时,您需要等待并阻止它,例如像这样:

    client.SendAsync(msg, msg)
    |> Async.AwaitTask // Converts Task<> to Async<>
    |> Async.RunSynchronously // Blocks until the async work is done.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      相关资源
      最近更新 更多