System.Net.Mail的性能问题

时间:2010-04-12 17:59:21

标签: vb.net performance system.net.mail

我从我的应用程序发送邮件时遇到了这个不寻常的问题。起初它没有工作(无法传递错误废话)无论如何我添加了正确的身份验证,它的工作原理。我现在的问题是,如果我尝试发送大约300封电子邮件(每封都有500k附件),那么该应用程序开始挂起95%左右。

以下是我发送的每封邮件的一些代码

 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

我在想,我可以准备好所有邮件并将它们添加到一个集合中然后打开一个SMTP连接并只是迭代集合,调用这样的发送

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

2 个答案:

答案 0 :(得分:1)

您遇到的限制是由SMTP服务器强制执行的,而不是您的代码。 SMTP服务器很容易被垃圾邮件滥用,因此有机制防止这种滥用。

单独发送每封电子邮件并不总是有效,您正在与其他更复杂的机制竞争。

但从技术上讲,是的,您可以编写一个单独发送它们的代码。

答案 1 :(得分:0)

对于您所谈论的大小和数量,我的建议是将它们放在SMTP可访问文件夹中,然后让SMTP服务器从该文件夹传递。那会更快更健全。

内存中的500K附件是一种资源密集型,并且在弹出时为300分配RAM大约是200MB RAM(用于保留资源,每次创建新消息,打开库等的开销)。所以第二个问题是你的服务器可以处理这个吗?只是观察。

相关问题