简体   繁体   中英

Send Email in background process

I have the following code that opens a page and sends emails to students registered in a class session with their attached certificates, generating the email and certificate works all in a different aspx page. Now, I'd like to generate the same process without the user waiting until all emails are sent, I'll add additional code in the process to notify me if there are any issues. Could anyone point me in the right direction to accomplish this. I have read a couple forums but mostly I have found windows services as an option which IMO it's a little over kill. I appreciate any suggestions

Thanks in advanced,

Dan

Protected Sub lbEmailOLetter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbEmailOLetter.Click


       Dim id As Integer
        id = hfSessionID.Value
        If id > 0 Then


            Try
                HttpContext.Current.Server.Execute("Email.aspx?SessID=" & id, False)
                HttpContext.Current.ApplicationInstance.CompleteRequest()


            Catch ex As Exception
                lMessage.Text = "Could not send email with attachment."
            End Try
        Else
            lMessage.Text = "Must create and save a session in order send letter by email."
        End If

    End Sub

您可以在服务器上运行一个单独的服务,您可以在其中发送要在队列中发送的电子邮件ID,以便该服务将异步处理该过程。

look into Task.Factory to spin this task off into another thread

example there are vbsamples there

You should look at Producer / Consumer patterns in .Net , specifically when using the Task Parallel Library.

I suggest using a shared (static) BlockingCollection ( bc ) container of a class modelling the content of your emails ( mailItem ), backed by the default ConcurrentQueue .

During launching of your App, eg in Application.Start in global.asax , place the code that your current Email.aspx page does to send emails, but instead it just loops through the queued mail items (it will block if there are none at the moment).

The background worker thread will look something like:

For Each mailItem In bc.GetConsumingEnumerable()
  ... send mail (Code from `Email.aspx`)
Next

And then on the page(s) which need to queue emails to be sent:

Dim mailItem as new MailItem()
mailItem.To = "mickey@mouse.com"
mailItem.Subject = ...
bc.Add(mailItem)

As each mailItem gets dropped onto the queue, the background thread will process it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM