DeveloperBarn Forums

DeveloperBarn

Programming & IT forum

Sending Email Asynchronously

This is a discussion on Sending Email Asynchronously within the .Net Development forums, part of the Programming & Scripting category; Hi peeps I have a page where user will make an update and it'll be saved in database and then ...

Go Back   DeveloperBarn Forums > Programming & Scripting > .Net Development

  #1  
Old June 24th, 2009, 05:17 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 563
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default Sending Email Asynchronously

Hi peeps
I have a page where user will make an update and it'll be saved in database and then it'll be sending emails to many members whose count can keep on increasing.

Should i write email sending code on that page only or use something else, because i dont want script timeout or something? Plus user need to send update again in say 20 minutes from that very page.

Anybody done anything like that before?
Suggestions and ideas are requested

Thanx

VB.NET 2.0
SQL Server 2005
__________________
Get the Mantra!
Reply With Quote
  #2  
Old June 24th, 2009, 06:01 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,312
Blog Entries: 5
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default

I have a similar system in place. If you have an email function in a global class and an email message class for properties like emailto, emailfrom, subject, message etc. then you can call this function for each user that needs to be sent an email, updating the emailto property of the email message class for each user....

You can set the function to send emails asynchronously, so, I believe, it doesn't wait for a response before continuing processing code.

Google "sending email asynchronously asp.net". If you need any help with the code, let me know.
__________________
Join the folding team
Reply With Quote
  #3  
Old June 24th, 2009, 06:11 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 563
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default

Thanx RR
Do you have some sample code, as i am little short on time on this one
Reply With Quote
  #4  
Old June 24th, 2009, 06:27 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,312
Blog Entries: 5
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default

Ok. You may need to make some changes but this is what I have:-
Code:
        Public Shared Sub SendAsync(ByVal email As EmailBOL, ByVal pcuser As Integer)
            Dim smtp As New SmtpClient
            Dim myMail As New MailMessage()
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network
            Dim arr_email_to As Array = Split(email.sentto, ";")
            For Each email_to As String In arr_email_to
                myMail.To.Add(New MailAddress(email_to))
            Next
            If Not String.IsNullOrEmpty(email.filepath) Then
                For Each item As String In Directory.GetFiles(email.filepath)
                    Dim mail_attach As Attachment = New Attachment(item)
                    myMail.Attachments.Add(mail_attach)
                Next
            End If
            'myMail.To.Add(txt_to.ToString)
            myMail.From = New MailAddress(email.from)
            myMail.IsBodyHtml = True
            If email.style = "client" Then
                myMail.Body = client_email_body(email.message)
            ElseIf email.style = "adviser" Then
                myMail.Body = adviser_email_body(email.message)
            ElseIf email.style = "intro" Then
                myMail.Body = client_email_body(email.message)
            Else
                myMail.Body = client_email_body(email.message)
            End If
            myMail.Subject = email.subject
            If email.own Then myMail.Bcc.Add(email.from)
            If email.read Then myMail.Headers.Add("Disposition-Notification-To", email.from)
            If Not String.IsNullOrEmpty(email.cc) Then myMail.CC.Add(email.cc)
            Dim mailBox As Object = myMail
            AddHandler smtp.SendCompleted, AddressOf SmtpClient_OnCompleted
            smtp.SendAsync(myMail, mailBox)
        End Sub
 
        Public Shared Function Send(ByVal email As EmailBOL, ByVal pcuser As Integer) As Boolean
            Dim smtp As New SmtpClient
            Dim myMail As New MailMessage()
            If email.checkerror Then
                Using myMail
                    Try
                        smtp.DeliveryMethod = SmtpDeliveryMethod.Network
                        Dim arr_email_to As Array = Split(email.sentto, ";")
                        For Each email_to As String In arr_email_to
                            myMail.To.Add(New MailAddress(email_to))
                        Next
                        If Not String.IsNullOrEmpty(email.filepath) Then
                            For Each item As String In Directory.GetFiles(email.filepath)
                                Dim mail_attach As Attachment = New Attachment(item)
                                myMail.Attachments.Add(mail_attach)
                            Next
                        End If
                        'myMail.To.Add(txt_to.ToString)
                        myMail.From = New MailAddress(email.from)
                        myMail.IsBodyHtml = True
                        If email.style = "client" Then
                            myMail.Body = client_email_body(email.message)
                        ElseIf email.style = "adviser" Then
                            myMail.Body = adviser_email_body(email.message)
                        ElseIf email.style = "intro" Then
                            myMail.Body = introducer_email_body(email.message)
                        Else
                            myMail.Body = client_email_body(email.message)
                        End If
                        myMail.Subject = email.subject
                        If email.own Then myMail.Bcc.Add(email.from)
                        If email.read Then myMail.Headers.Add("Disposition-Notification-To", email.from)
                        If Not String.IsNullOrEmpty(email.cc) Then myMail.CC.Add(email.cc)
                        smtp.Send(myMail)
                    Catch ex As Exception
                        email.page_error = "Your email has not been sent<br />" & ex.ToString & "<br />" & email.sentto
                    End Try
                End Using
            Else
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network
                Dim arr_email_to As Array = Split(email.sentto, ";")
                For Each email_to As String In arr_email_to
                    myMail.To.Add(New MailAddress(email_to))
                Next
                If Not String.IsNullOrEmpty(email.filepath) Then
                    For Each item As String In Directory.GetFiles(email.filepath)
                        Dim mail_attach As Attachment = New Attachment(item)
                        myMail.Attachments.Add(mail_attach)
                    Next
                End If
                'myMail.To.Add(txt_to.ToString)
                myMail.From = New MailAddress(email.from)
                myMail.IsBodyHtml = True
                If email.style = "client" Then
                    myMail.Body = client_email_body(email.message)
                ElseIf email.style = "adviser" Then
                    myMail.Body = adviser_email_body(email.message)
                ElseIf email.style = "intro" Then
                    myMail.Body = client_email_body(email.message)
                Else
                    myMail.Body = client_email_body(email.message)
                End If
                myMail.Subject = email.subject
                If email.own Then myMail.Bcc.Add(email.from)
                If email.read Then myMail.Headers.Add("Disposition-Notification-To", email.from)
                If Not String.IsNullOrEmpty(email.cc) Then myMail.CC.Add(email.cc)
                Dim mailBox As Object = myMail
                AddHandler smtp.SendCompleted, AddressOf SmtpClient_OnCompleted
                smtp.SendAsync(myMail, mailBox)
                'smtp.Send(myMail)
            End If
 
            If String.IsNullOrEmpty(email.page_error) Then
                Return True
            Else
                Return False
            End If
 
        End Function
 
        Public Shared Function func_getfilename(ByVal str_file As String) As String
            Dim arr_file As Array = Split(str_file, "\")
            Return arr_file(UBound(arr_file))
        End Function
Then the EmailBOL is:-
Code:
Namespace myApp.App.BOL
    Public Class EmailBOL
        Private _error As String = String.Empty
        Public Property page_error() As String
            Get
                Return _error
            End Get
            Set(ByVal value As String)
                _error = value
            End Set
        End Property
        Private _emailref As Integer = 0
        Public Property emailref() As Integer
            Get
                Return _emailref
            End Get
            Set(ByVal value As Integer)
                _emailref = value
            End Set
        End Property
        Private _checkerror As Boolean = True
        Public Property checkerror() As Boolean
            Get
                Return _checkerror
            End Get
            Set(ByVal value As Boolean)
                _checkerror = value
            End Set
        End Property
        Private _visitorref As Integer = 0
        Public Property visitorref() As Integer
            Get
                Return _visitorref
            End Get
            Set(ByVal value As Integer)
                _visitorref = value
            End Set
        End Property
        Private _introref As Integer = 0
        Public Property introref() As Integer
            Get
                Return _introref
            End Get
            Set(ByVal value As Integer)
                _introref = value
            End Set
        End Property
        Private _sentby As Integer = 0
        Public Property sentby() As Integer
            Get
                Return _sentby
            End Get
            Set(ByVal value As Integer)
                _sentby = value
            End Set
        End Property
        Private _priority As Integer = 0
        Public Property priority() As Integer
            Get
                Return _priority
            End Get
            Set(ByVal value As Integer)
                _priority = value
            End Set
        End Property
        Private _completedby As Integer = 0
        Public Property completedby() As Integer
            Get
                Return _completedby
            End Get
            Set(ByVal value As Integer)
                _completedby = value
            End Set
        End Property
        Private _from As String = String.Empty
        Public Property from() As String
            Get
                Return _from
            End Get
            Set(ByVal value As String)
                _from = value
            End Set
        End Property
        Private _sentto As String = String.Empty
        Public Property sentto() As String
            Get
                Return _sentto
            End Get
            Set(ByVal value As String)
                _sentto = value
            End Set
        End Property
        Private _cc As String = String.Empty
        Public Property cc() As String
            Get
                Return _cc
            End Get
            Set(ByVal value As String)
                _cc = value
            End Set
        End Property
        Private _subject As String = String.Empty
        Public Property subject() As String
            Get
                Return _subject
            End Get
            Set(ByVal value As String)
                _subject = value
            End Set
        End Property
        Private _message As String = String.Empty
        Public Property message() As String
            Get
                Return _message
            End Get
            Set(ByVal value As String)
                _message = value
            End Set
        End Property
        Private _sentby_str As String = String.Empty
        Public Property sentby_str() As String
            Get
                Return _sentby_str
            End Get
            Set(ByVal value As String)
                _sentby_str = value
            End Set
        End Property
        Private _sentby_email As String = String.Empty
        Public Property sentby_email() As String
            Get
                Return _sentby_email
            End Get
            Set(ByVal value As String)
                _sentby_email = value
            End Set
        End Property
        Private _attach As String = String.Empty
        Public Property attach() As String
            Get
                Return _attach
            End Get
            Set(ByVal value As String)
                _attach = value
            End Set
        End Property
        Private _filepath As String = String.Empty
        Public Property filepath() As String
            Get
                Return _filepath
            End Get
            Set(ByVal value As String)
                _filepath = value
            End Set
        End Property
        Private _style As String = String.Empty
        Public Property style() As String
            Get
                Return _style
            End Get
            Set(ByVal value As String)
                _style = value
            End Set
        End Property
        Private _sentitems As Boolean = False
        Public Property sentitems() As Boolean
            Get
                Return _sentitems
            End Get
            Set(ByVal value As Boolean)
                _sentitems = value
            End Set
        End Property
        Private _own As Boolean = False
        Public Property own() As Boolean
            Get
                Return _own
            End Get
            Set(ByVal value As Boolean)
                _own = value
            End Set
        End Property
        Private _read As Boolean = False
        Public Property read() As Boolean
            Get
                Return _read
            End Get
            Set(ByVal value As Boolean)
                _read = value
            End Set
        End Property
        Private _datesent As Nullable(Of DateTime) = Nothing
        Public Property datesent() As Nullable(Of DateTime)
            Get
                Return _datesent
            End Get
            Set(ByVal value As Nullable(Of DateTime))
                _datesent = value
            End Set
        End Property
    End Class
End Namespace
You can probably remove quite a few of the properties. Mine links into which users have sent the email and saves them in a sentitems db table. Most of the properties should make sense. The checkerror boolean toggles whether to send asynchronous or not. Basically if you set checkerror to false it sends asynchronously.

Hope that helps. Let me know if it needs explaining.

Comments on this post
micky agrees: Thanked Post
Reply With Quote
The Following User Says Thank You to richyrich For This Useful Post:
micky (June 24th, 2009)
  #5  
Old June 24th, 2009, 06:40 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 563
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default

Thanx a lot RR.
So you have this function SendAsync kept in some file in app_code folder?

Then you call it from any page and this function will keep on sending on emails without blocking that initial page and also would skip to next if faced any problem when sending to any email address?

Do i need subroutine named SmtpClient_OnCompleted also?
Last thing, i'll have to supply this code all the emails before hand??
Reply With Quote
  #6  
Old June 24th, 2009, 06:59 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,312
Blog Entries: 5
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default

Sorry, yes, all the functions and classes are in a file in App_Code.

And you will also need
Code:
        Public Shared Sub SmtpClient_OnCompleted(ByVal s As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
            'Get the Original MailMessage object
            Dim mail As MailMessage = CType(e.UserState, MailMessage)
            'write out the subject
            Dim subject As String = mail.Subject
            If e.Cancelled Then
                Console.WriteLine("Send cancelled 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
You only call the Send function from your page (after importing the appropriate namespace) and when passing the emailBOL class type to the function, set the checkerror property to false if you want it to send asynchronously or true if you don't.

You create an instance of the EmailBOL class in your page, set the properties of it:-
email.from
email.sendto
email.subject
email.message
etc.

and then send this as the first parameter of the Send function. The second parameter you can get rid of. That was just for me to pass the user that was sending the email for sent items purposes.

Does that make sense?
Reply With Quote
  #7  
Old June 24th, 2009, 07:07 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 563
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default

Makes lot of sense RR

May i ask why you have 2 functions, Send and SendAsync ??
I must use the SendAsync, i think.

Also, i'll have to supply this code all the emails before hand as an array??
Reply With Quote
  #8  
Old June 24th, 2009, 07:39 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,312
Blog Entries: 5
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default

I got the async code from somewhere else, try googling and I think it's not a straightforward function. Hence why the call is to another function that then calls the async function.

Try googling sending asynchronously and you may find some more info. I'm pretty certain you can't call it directly though.

For passing the email addresses, you can just put them all in the sendto string as email1@domain.com;email2@domain.com;email3@domain. com etc. and the function splits them all off and sends a seperate email to each.
Reply With Quote
  #9  
Old June 24th, 2009, 07:42 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 563
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default

ok, thanx a lot RR

i'll get back if i need help
Reply With Quote
  #10  
Old June 24th, 2009, 08:10 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,312
Blog Entries: 5
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default

Quote:
Originally Posted by micky View Post
ok, thanx a lot RR

i'll get back if i need help
No problem m....Let me know how it goes...
Reply With Quote
Reply

  DeveloperBarn Forums > Programming & Scripting > .Net Development

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads

Thread Thread Starter Forum Replies Last Post
Sending Emails Using ASP.NET richyrich .Net Code Samples 5 July 6th, 2009 04:21 AM
[Email] Sending HTML email... bryceowen PHP Development 3 April 8th, 2009 07:28 PM
Excel and Email Chrissy ASP Development 10 February 16th, 2009 09:11 PM
Sending Email with ASP and CDOSYS jmurrayhead ASP Code Samples 1 November 13th, 2008 09:26 AM
Sending Email using CDOSYS & Classic ASP richyrich ASP Code Samples 0 March 17th, 2008 09:52 AM


All times are GMT -4. The time now is 02:04 AM.


Copyright ©2008-2009, DeveloperBarn

Content Relevant URLs by vBSEO 3.3.2