I am trying to send daily mail alert to users based on some timer values. For that I've used Addhandler
to call the sendmail()
function on timer Tick
. In this scenario I faced a problem and I am unable to pass arguments to the function through AddressOf
.
What I wanted was to use my function, which took these parameters…
Public Sub SendMail(ByVal UserMailId As String,
ByVal UserPassword As String,
ByVal HostName As String,
ByVal HostPort As String)
by calling it using AddHandler mailTimer.Elapsed, AddressOf userDetails.SendMail(parameters)
, but that failed with an error:
'AddressOf' Operand name must be the name of the method without parenthesis
After some research, here's my solution for this problem:
Dim userDetails As New Details
' These values are from database that will changed based on some conditions given
' now it is hardcoded for an example
userDetails.HostName = "smtp.gmail.com"
userDetails.HostPort = "587"
userDetails.UserMailId = "[email protected]"
userDetails.UserPassword = "mymailPasswo6d"
Dim mailTimer As System.Timers.Timer
mailTimer.Interval = 18000
AddHandler mailTimer.Elapsed, AddressOf userDetails.SendMail
mailTimer.Start()
Where Details
is the class which is defined as follows:
Class Details
Public UserMailId As String
Public UserPassword As String
Public HostName As String
Public HostPort As String
Public Sub SendMail()
Try
Dim smtpServer As New SmtpClient
Dim eMail As New MailMessage()
smtpServer.UseDefaultCredentials = False
smtpServer.Credentials = New Net.NetworkCredential(UserMailId, UserPassword)
smtpServer.Port = HostPort
smtpServer.EnableSsl = True
smtpServer.Host = HostName
eMail = New MailMessage()
eMail.From = New MailAddress(UserMailId)
eMail.To.Add(txtemailTo.Text)
eMail.Subject = "Test Mail"
eMail.IsBodyHtml = False
eMail.Body = txtMessage.Text
smtpServer.Send(eMail)
MsgBox("Mail Sent")
Catch errorT As Exception
MsgBox(errorT.ToString)
End Try
End Sub
End Class
Now what my question is:
- Is the method I was using the correct one? Is there any simple or alternate solution for this?
- Can anyone please review the code to improve it? It gives me better results but I think some modification is required.