Smtp clients `SendAsync ()` method

 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 smtp clients function SendAsync()

to send asynchronous emails ... but this function doesn't work ... why? i don't receive any emails ... when i send it synchronously ... i receive emails it means my settings are correct ... so what's wrong with the methodSendAsync()

+3


source to share


1 answer


I do this all the time, and after years of work, I offer (2) a multiple solution to your problem:

  • Refactoring the actual postcode submission (System.Net stuff) to a WCF service or a separate .dll (I prefer this service).
  • Continue to use your asynchronous delegate call from the ASP.NET page, but do so in "fire-and-forget" mode, where you don't wire callbacks.

You might say that you need to know that something went wrong with the sending of the email. Let the WCF service sending emails handle this. Perform any logging on the service. In the end, everything you really did anyway was logged. If you need to get an optimistic workflow if the message is not working there are ways your ASP.NET can be flagged, but I think you will find that after the messaging service is stable you will have very few problems ...



In fact, I have been doing this exact method for years, using a service called ASP.NET to send emails and have sent 10 thousand different emails and have never had any problems with this design with paying and forgetting.

Finally, setting the page Async=True

forces the page to act synchronously as a whole, blocking the main thread until the entire asynchronous process has completed. This can make pages very slow to load and is usually unnecessary.

0


source







All Articles