在.NET中调用SmtpClient.Dispose()是否安全?

时间:2013-01-17 22:56:12

标签: vb.net email smtp

我有一个场景,我需要一次发送100封电子邮件(使用循环),但我也不允许每个SMTP会话发送1封电子邮件。

现在所有100封电子邮件共享相同的SMTP会话。

我在想,调用SmtpClient.Dispose()会照顾我需要的东西。如果我错了,请纠正我。

所以,基本上有3个问题:

  1. SmtpClient.Dispose()会照顾我需要的吗?
  2. 如果是,在不影响其他服务的情况下Dispose()SmtpClient是否安全 服务器?
  3. 如果否,那么实现目标的方法是什么? 想?
  4. 示例代码:

    Private Shared Sub SendMail(ByVal MailServer As SmtpClient, ByVal body As String, ByVal Subject As String, ByVal FromEmail As String, _
                                   ByVal ToEmailList As String, Optional ByVal AttFile As Attachment = Nothing)
    
        Dim message As New MailMessage
    
        Try
            message.From = New MailAddress(FromEmail)
    
            message.Subject = Subject
            message.IsBodyHtml = False
            message.Body = body
            message.Priority = MailPriority.High
    
            If Not AttFile Is Nothing Then
                message.Attachments.Add(AttFile)
            Else
                message.Attachments.Add(AttFile)
            End If
    
            MailServer.Send(message)
        Catch ex As Exception
            Throw New ApplicationException("SERVICE1.SendMail ERROR -- Error sending email [ERROR]:[" & ex.Message.ToString & "] " & vbCrLf & "To:" & ToEmailList & vbCrLf & "From:" & FromEmail & vbCrLf & "Subject: " & Subject & vbCrLf & "Body: " & body)
        End Try
        message.Dispose()
    End Sub
    

    这就是方法的执行方式:

     For Each Item In ItemListCollection
     m_MailServer = New SmtpClient(MailServerName)
     MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
     SendMail(WeeklyMailServer, msgBody, msgSubject, MsgFromEmail, "xyz@abc.com", rptAttachment)
     Next
    

2 个答案:

答案 0 :(得分:3)

您可以将其包装在using语句中,并确保在执行离开块时将其处理掉。您可以使用相同的SmtpClient在循环中多次调用Send。

Using client = New SmtpClient()

    For i As Integer = 0 To 99
        Dim message = New MailMessage()
        'initialization of whatever is needed
        ' message creation

        client.Send(message)

    Next
End Using

答案 1 :(得分:1)

在内部执行循环中,您可以将代码括在Using块中。这将为每封电子邮件使用单独的smtpclient,并将正确处理/关闭它。

 For Each Item In ItemListCollection
   using m_MailServer as New SmtpClient(MailServerName)
     MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
     SendMail(WeeklyMailServer, msgBody, msgSubject, MsgFromEmail, "xyz@abc.com", rptAttachment)
   end using
   Next