How to use streams

I am trying to send an email on a button click ... but I want to send emails in the background as the number of emails is too large ... so I am using threading.

Public Sub sendEmail()
     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
             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("asdf@asdf.com")
             message.To.Add(New MailAddress(_table.Rows(i).Item(1)))
             'message.CC.Add(New MailAddress("monodeep12@gmail.com"))
             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.asdf.com"
             'smtp.gmail.com
             client.Port = 25
             client.UseDefaultCredentials = True
             client.Credentials = New System.Net.NetworkCredential("asdf@asdf.com", "123456")
             'smtp.EnableSsl = True
             client.Send(message)
             i += 1
         Next
     Catch ex As Exception
         Response.Write(ex.Message)
     End Try
 End Sub

      

Table structure

Sno
email
URL
ReporterName

I am using below script in button click event

 Dim thread As New System.Threading.Thread(AddressOf sendEmail)
 Thread.IsBackground = True
 Thread.Start()
 Thread.Priority = System.Threading.ThreadPriority.Normal

      

Am I doing it right? Since I am not getting any errors and emails :(

0


source to share


1 answer


There are more efficient approaches than manually creating a stream.



First, I have to make sure the actual submit process is running on the same thread. Multi-threaded applications are much more difficult to debug.

0


source







All Articles