smtp clients `SendAsync()` method

萝らか妹 提交于 2019-12-22 10:24:57

问题


 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

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??


回答1:


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

  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.

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.

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.

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.



来源:https://stackoverflow.com/questions/9756443/smtp-clients-sendasync-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!