Monday, December 8, 2008

Alert using SMTP

There are so many reasons why people send email but the reasons are not so vary why machines send email. One of the most popular reason is to give an alert of some particular events. As in my case I used to create a vb.net program to send an email to alert me on some events happen in the server I'm currently in charged. For instance, I will be able to know how much free space of the C: drive of the server left at the moment I received the alert. This will help me a lot so that the server won't hang once it reach the maximum size, since I can take some actions long before it happens.

To make your vb.net application to send email is not so hard. Maybe below codes might help.


Public g_EMAIL_SMTP As String = "smtp.bizmail.yahoo.com"
Public g_EMAIL_Port As String = "587"
Public g_EMAIL_Sender As String = "alert@mail.com"
Public g_EMAIL_Desc As String = ""
Public g_EMAIL_User As String = "nasrul@mail.com.my"
Public g_EMAIL_Pwd As String = "abc1234"

Public Function Send_EMAIL(ByVal strEmailaddr As String, ByVal strSubject As String, ByVal strBody As String) As Boolean
Dim oMessage As New MailMessage()

oMessage.Subject = g_EMAIL_Desc + " - " + strSubject
oMessage.Body = strBody + " on " + Now().ToString()
oMessage.IsBodyHtml = False
oMessage.ReplyTo = New MailAddress(g_EMAIL_Sender)
oMessage.From = New MailAddress(g_EMAIL_Sender)
Dim arrRcpt() As String
Dim i As Integer
arrRcpt = Split(strEmailaddr, ",")
For i = 0 To UBound(arrRcpt)
If arrRcpt(i) <> "" Then
oMessage.To.Add(New MailAddress(arrRcpt(i)))
End If
Next
oMessage.Priority = MailPriority.High

Try
Dim client As New SmtpClient(g_EMAIL_SMTP, g_EMAIL_Port)
If g_EMAIL_User.Trim <> "-" And g_EMAIL_Pwd.Trim <> "-" Then
client.Credentials = New Net.NetworkCredential(g_EMAIL_User.Trim, g_EMAIL_Pwd.Trim)

End If
client.Send(oMessage)
Catch ex As Exception

Return False
End Try

Return True
End Function

From anywhere of you codes, you just call this function, and if all the SMTP settings are correct, the email will be successfully sent to the recipient!

If you're going to send an alert email, remember to set the filter, so that the application won't simply send the email which might flood your inbox. As in my case where the apps alert me the server hard drive free space, the email will only be sent once the application notice that the free space left is less than 80 GB.

Dim FreeSpace As String = My.Computer.FileSystem.Drives.Item(0).AvailableFreeSpace.ToString
Dim fspaceInMB As Double = Math.Round((CDbl(FreeSpace) / 1000000), 2)
Dim fspaceInGB As Double = Math.Round((CDbl(FreeSpace) / 1000000000), 2)
Dim strBody As String = ""

fspaceInMB = fspaceInMB - 1000
fspaceInGB = fspaceInGB - 1

If CDbl(fspaceInGB) <>
Send_EMAIL("helangtimuran@gmail.com", "WARNING: Hard disk almost full", "")
End If


In this way, the apps. not only give you an alert but it gives you an alert in an efficient way.







No comments: