Performance problem with System.Net.Mail

Posted by Saif Khan on Stack Overflow See other posts from Stack Overflow or by Saif Khan
Published on 2010-04-12T17:59:21Z Indexed on 2010/04/12 18:03 UTC
Read the original article Hit count: 435

I have this unusual problem with mailing from my app. At first it wasn't working (getting unable to relay error crap) anyways I added the proper authentication and it works. My problem now is, if I try to send around 300 emails (each with a 500k attachment) the app starts hanging around 95% thru the process.

Here is some of my code which is called for each mail to be sent

 Using mail As New MailMessage()
            With mail
                .From = New MailAddress(My.Resources.EmailFrom)
                For Each contact As Contact In Contacts
                    .To.Add(contact.Email)
                Next
                .Subject = "Accounting"
                .Body = My.Resources.EmailBody
                'Back the stream up to the beginning orelse the attachment
                'will be sent as a zero (0) byte file.
                attachment.Seek(0, SeekOrigin.Begin)
                .Attachments.Add(New Attachment(attachment, String.Concat(Item.Year, Item.AttachmentType.Extension)))
            End With
            Dim smtp As New SmtpClient("192.168.1.2")
            With smtp
                .DeliveryMethod = SmtpDeliveryMethod.Network
                .UseDefaultCredentials = False
                .Credentials = New NetworkCredential("username", "password")
                .Send(mail)
            End With
        End Using
        With item
            .SentStatus = True
            .DateSent = DateTime.Now.Date
            .Save()
        End With
        Return

I was thinking, can I just prepare all the mails and add them to a collection then open one SMTP conenction and just iterate the collection, calling the send like this

Using mail As New MailMessage()
 ...
MailCollection.Add(mail)

End Using

...

                Dim smtp As New SmtpClient("192.168.1.2")
                With smtp
                    .DeliveryMethod = SmtpDeliveryMethod.Network
                    .UseDefaultCredentials = False
                    .Credentials = New NetworkCredential("username", "password")

                     For Each mail in MainCollection
                          .Send(mail)
                     Next

                End With

© Stack Overflow or respective owner

Related posts about system.net.mail

Related posts about vb.net