Monday 13 July 2015

VB.NET :: mengirim Email dengan Multiple Threads(Mass Mail) in VB.NET


Imports EASendMail 'Add EASendMail namespace

Module Module1
Sub Main()
Dim arRcpt() As String = {"test1@adminsystem.com", _
"test2@adminsystem.com", _
"test3@adminsystem.com"}

Dim nRcpt As Integer = arRcpt.Length
Dim arMail(nRcpt - 1) As SmtpMail
Dim arSmtp(nRcpt - 1) As SmtpClient
Dim arResult(nRcpt - 1) As SmtpClientAsyncResult

For i As Integer = 0 To nRcpt - 1
arMail(i) = New SmtpMail("TryIt")
arSmtp(i) = New SmtpClient()
Next

For i As Integer = 0 To nRcpt - 1

Dim oMail As SmtpMail = arMail(i)
' Set sender email address
oMail.From = "sender@emailarchitect.net"

' Set recipient email address
oMail.To = arRcpt(i)

' Set email subject
oMail.Subject = "mass email test from vb.net"

' Set email body
oMail.TextBody = "test from VB, this email is sent to " + arRcpt(i)

' Your SMTP server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")

' User and password for ESMTP authentication, if your server doesn't require
' User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"

' If your smtp server requires SSL/TLS connection, please add this line
' oServer.ConnectType = SmtpConnectType.ConnectSSLAuto

Dim oSmtp As SmtpClient = arSmtp(i)

' Submit email to BeginSendMail method and return
' to process another email
arResult(i) = oSmtp.BeginSendMail(oServer, oMail, Nothing, Nothing)
Console.WriteLine(String.Format("Start to send email to {0} ...", _
arRcpt(i)))
Next

' all emails were sent by BeginSendMail Method
' now get result by EndSendMail method
Dim nSent As Integer = 0
Do While (nSent < nRcpt)

For i As Integer = 0 To nRcpt - 1
' this email is finished
If (arResult(i) Is Nothing) Then
Continue For
End If

' wait for specified email ...
If (Not arResult(i).AsyncWaitHandle.WaitOne(10, False)) Then
Continue For
End If

Try
' this email is finished, using EndSendMail to get result
arSmtp(i).EndSendMail(arResult(i))
Console.WriteLine(String.Format("Send email to {0} successfully", _
arRcpt(i)))

Catch ep As Exception

Console.WriteLine( _
String.Format("Failed to send email to {0} with error {1}: ", _
arRcpt(i), ep.Message))
End Try

' Set this email result to null, then it won't be processed again
arResult(i) = Nothing
nSent += 1
Next
Loop

End Sub
End Module

No comments:

Post a Comment