我有一个场景,我需要一次发送100封电子邮件(使用循环),但我也不允许每个SMTP会话发送1封电子邮件。
现在所有100封电子邮件共享相同的SMTP会话。
我在想,调用SmtpClient.Dispose()会照顾我需要的东西。如果我错了,请纠正我。
所以,基本上有3个问题:
示例代码:
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
答案 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