smtp客户端的"SendAsync()"方法 [英] smtp clients `SendAsync()` method

查看:213
本文介绍了smtp客户端的"SendAsync()"方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 Protected Sub btnLocalSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLocalSubmit.Click

            Dim logic = New connections
            logic.emailsToSend(User.Identity.Name, getURL, reportedBy)
            SendAsync()
            Response.Redirect(getRedirectionPath, False)
        Catch ex As Exception
            Response.Write(ex.Message)
        Finally
            _con.Close()
            _con.Dispose()
            _sqlComm.Dispose()

        End Try
    End Sub

    Sub SendAsync()

        Dim _con As New SqlConnection(ConfigurationManager.ConnectionStrings("CitizenJDBConnectionString").ConnectionString)
        Dim _sqlDataAdapter As New SqlDataAdapter("SELECT * FROM EmailSender", _con)
        Dim _table As New System.Data.DataTable

        Try
            _con.Open()
            _sqlDataAdapter.Fill(_table)
            _con.Close()

            For i As Integer = 0 To _table.Rows.Count - 1


                Dim AppPath As String = Request.PhysicalApplicationPath

                Dim sr As New StreamReader(AppPath & "EmailTemplates/NewReport.txt")
                Dim message As New MailMessage()

                message.IsBodyHtml = True

                message.From = New MailAddress("admin@xxxx.com")

                message.To.Add(New MailAddress(_table.Rows(i).Item(1)))


                message.Subject = "New User registration !"

                message.Body = sr.ReadToEnd()

                sr.Close()

                message.Body = message.Body.Replace("<%ReporterName%>", _table.Rows(i).Item(3))

                message.Body = message.Body.Replace("<%ReportURL%>", _table.Rows(i).Item(2))

                Dim client As New SmtpClient()
                client.Host = "smtp.xxxxx.com"
                'smtp.gmail.com
                client.Port = 25
                client.UseDefaultCredentials = True
                client.Credentials = New System.Net.NetworkCredential("admin@xxxx.com", "123456")
                'client.EnableSsl = True
                Dim userState As Object = message

                'wire up the event for when the Async send is completed
                AddHandler client.SendCompleted, AddressOf SmtpClient_OnCompleted

                client.SendAsync(message, userState)

            Next

        Catch ex As Exception
            Response.Write(ex.Message)
        End Try


    End Sub 'SendAsync

    Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
        'Get the Original MailMessage object
        Dim message As MailMessage = CType(e.UserState, MailMessage)

        'write out the subject
        Dim subject As String = message.Subject

        If e.Cancelled Then
            Console.WriteLine("Send canceled for mail with subject [{0}].", subject)
        End If
        If Not (e.Error Is Nothing) Then
            Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString())
        Else
            Console.WriteLine("Message [{0}] sent.", subject)
        End If
    End Sub 'SmtpClient_OnCompleted

我正在使用smtp客户端 SendAsync()函数异步发送电子邮件...但是此函数不起作用...为什么?我没有收到任何电子邮件..当我同步发送它时...我收到了电子邮件,这意味着我的设置是正确的...所以 SendAsync()方法有什么问题吗?

I am using the smtp clients SendAsync() function to send out emails asynchronously...but this function does not work ...why?? i do not get any email..when i send it Synchronously...i get the emails, this means my settings are correct...so what is wrong with the SendAsync() method??

推荐答案

我一直这样做,经过数年的努力,我建议针对您的问题提供(2)折的解决方案:

I do this all the time, and after years of doing this I suggest a (2) fold solution to your problem:

  1. 重构将 actual 发送电子邮件代码(System.Net的东西)到WCF服务或单独的.dll(我更喜欢该服务)中.
  2. 继续从ASP.NET页使用异步委托调用,但是以即发即弃"的方式进行,无需连接任何回调.
  1. Refactor the actual sending email code (System.Net stuff) into a WCF service or separate .dll (I prefer the service).
  2. Continue to use your asynchronous delegate call from your ASP.NET page but do so in a 'fire-and-forget' manner where you do not wire up any callbacks.

您可能会说您需要知道发送电子邮件是否有问题.让发送电子邮件的WCF服务对此进行处理.在服务中进行任何登录.毕竟,无论如何,您真正要做的就是记录日志.如果您需要在电子邮件失败的情况下提高工作流程的效率,可以使用多种方法来标记ASP.NET,但是我认为您会发现,一旦发送电子邮件的服务稳定之后,您将遇到很少的问题.

You might say you need to know if something went wrong with sending the email. Let the WCF service that sends the emails handle this. Do any logging in the service. After all that's all you were really doing anyways was logging. If you need to get fancier with a workflow if the email fails, there are ways that your ASP.NET can be flagged, but I think you will find that once the service to send the emails is stable, you will have very few problems.

事实上,多年来,我一直在使用ASP.NET调用的服务来发送电子邮件,并且已经发送了成千上万种不同的电子邮件,而这种精确的方法一直在使用这种精确的方法.

In fact I have been doing this exact method for years using a service called by ASP.NET to send emails and have sent 10 of thousands of differing emails and never had any problem with this fire-and-forget design.

最后,设置页面 Async = True 最终将阻止主线程,直到所有异步过程完成,从而使页面最终整体同步.这会使页面加载非常缓慢,通常是不希望的.

And lastly, setting the page Async=True makes the page act overall synchronously in the end by blocking the main thread until all asynchronous process are completed. This can make the pages very slow to load and is typically not desired.

这篇关于smtp客户端的"SendAsync()"方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆