Sand mail using service in VB.Net

Sand mail with particular day and time using service in VB.Net

First add installer and set properties
Add Log.dll file for log entry(It's not compulsory )
This service send mail automatically monday to friday with 8 am to 11 am per hours. It mean 8,9,10,11.

'app.config file code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>

</sharedListeners>
</system.diagnostics>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<appSettings>

<add key="MSSqlConStr" value="Data Source=Amit\SQLEXPRESS;Initial Catalog=UserCreation;User Id=sarkar;Password=sarkar;" />
<add key="MySqlConStr" value="" />
<add key="SqlConnectionPool" value="15" />
<add key="FromAddr" value="[email protected]" />
<add key ="ToAddr" value ="[email protected]"/>
<add key="EmailPort" value="25" />
<add key="EmailPort1" value ="25"/>
<add key ="Emailport2" value =""/>
<add key="ServiceRun_FromTime" value="08:00:00 AM"/>
<add key="ServiceRun_ToTime" value="11:00:00 AM"/>
'This code for send mail using day
<add key="ServiceRun_Days" value="mon,tue,wed,thu,fri"/>
<add key ="ServiceRunInterval" value ="60000"/>
<add key =""/>
</appSettings>
</configuration>


'Service1.vb code

'Namespace Declaration
#Region "Namespace"
Imports Log.Log
Imports DAL
Imports System.Text
Imports System.Timers
Imports System.IO
Imports System.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
#End Region

Public Class Service1

'Variables Declaration
#Region "Variables"
Dim tmrOrderStatus As Timer = Nothing
Dim objDAL As MSSqlHelper = Nothing
Dim StrMail As StringBuilder
Dim ServiceRun_Days As String = Nothing
Dim ServiceRun_FromTime As DateTime = Nothing
Dim ServiceRun_ToTime As DateTime = Nothing
Dim ServiceRunInterval As Long
'Dim objOra As OracleConnection
Dim toAddr, fromAddr, ccAddr As String
Dim NewName As String
#End Region

#Region "Service Events"
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Try
WriteLog("UserStatusService Started Successfully...")
If Int64.TryParse(ConfigurationManager.AppSettings.Get("PumpingInterval"), ServiceRunInterval) = False Then
ServiceRunInterval = 60000 * 60
End If
ServiceRun_Days = TryCast(ConfigurationManager.AppSettings.Get("ServiceRun_Days"), String)
If String.IsNullOrEmpty(ServiceRun_Days) = True Then ServiceRun_Days = "mon,tue,wed,thu,fri"
ServiceRun_Days = ServiceRun_Days.ToLower
tmrOrderStatus = New System.Timers.Timer
If Now.Minute = 0 Then
tmrOrderStatus.Interval = 0
Else
tmrOrderStatus.Interval = (60 - Now.Minute) * 1000
End If

tmrOrderStatus.Enabled = True
AddHandler tmrOrderStatus.Elapsed, AddressOf tmrOrderStatus_Elapsed
Catch ex As Exception
'This function Create a log entry
WriteLog(ex.ToString, EventLogEntryType.Error)
End Try
End Sub

Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
Try
WriteLog("Service stopped Successfully")
Catch ex As Exception
WriteLog(ex.ToString(), EventLogEntryType.Error)
End Try
    End Sub
#End Region

#Region "Internal Functions"
''' <summary>
''' Generate Mail and get the Details
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks>Created By Amit Patel</remarks>
Private Sub tmrOrderStatus_Elapsed(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)
Try
If tmrOrderStatus.Interval <> 60000 * 60 Then tmrOrderStatus.Interval = 60000 * 60
If ServiceRun_Days.Contains(Now.ToString("ddd").ToLower) = False Then Exit Sub
If DateTime.TryParse(ConfigurationManager.AppSettings.Get("ServiceRun_FromTime"), ServiceRun_FromTime) = False Then
ServiceRun_FromTime = New DateTime(Now.Year, Now.Month, Now.Day, 16, 0, 0)
End If
If DateTime.TryParse(ConfigurationManager.AppSettings.Get("ServiceRun_ToTime"), ServiceRun_ToTime) = False Then
ServiceRun_ToTime = New DateTime(Now.Year, Now.Month, Now.Day, 20, 0, 0)
End If
If DateTime.Compare(Now, ServiceRun_FromTime) < 0 OrElse DateTime.Compare(Now, ServiceRun_ToTime) > 0 Then Exit Sub
Dim result1 As String

WriteLog("getresult1")
result1 = getResult1()

WriteLog("Mail")
If SendMail(result1) = True Then
WriteLog("Mail Send To    : " & toAddr)
WriteLog("Mail Send From  : " & fromAddr)
Else
WriteLog("Error in Sending Mail...")
End If
Catch ex As Exception
WriteLog(ex.ToString, EventLogEntryType.Error)
End Try
End Sub

Private Function SendMail(ByVal result1 As String) As Boolean
Try
SendMail = False
Dim mail As New Mail.MailMessage()
toAddr = ConfigurationManager.AppSettings.Get("ToAddr")
If String.IsNullOrEmpty(toAddr) = True Then
toAddr = "[email protected]"
End If
mail.To.Add(toAddr)
fromAddr = ConfigurationManager.AppSettings.Get("FromAddr")
If String.IsNullOrEmpty(fromAddr) = True Then
fromAddr = "[email protected]"
End If

mail.From = New Mail.MailAddress(fromAddr, "Amit Patel", System.Text.Encoding.UTF8)

mail.IsBodyHtml = True
mail.Subject = "User Reconciliation Status"
'create Body
StrMail = New StringBuilder()
StrMail.AppendLine("<pre>Dear Ranna,")
StrMail.AppendLine(" ")
StrMail.AppendLine("User Processing Status at " & Now.ToString("hh:mm tt") & " of " & Now.ToString("dd-MMM-yyyy") & ",")
StrMail.AppendLine(" ")
StrMail.AppendLine("User Name             :  " & result1.ToString().PadLeft(3))
StrMail.AppendLine(" ")
StrMail.AppendLine("Thanks & Regards")
StrMail.AppendLine("Amit Patel")
StrMail.AppendLine("Software Developer | Baroda | India.")
StrMail.AppendLine("Ext.- 9033323299</pre>")
mail.Body = StrMail.ToString()
mail.BodyEncoding = System.Text.Encoding.UTF8
mail.Priority = Net.Mail.MailPriority.High
Dim client As New Mail.SmtpClient()
client.Credentials = New System.Net.NetworkCredential("Your Email Id", "Password")
Dim port As String = ConfigurationManager.AppSettings.Get("EmailPort")
If String.IsNullOrEmpty(port) = True Then
client.Port = 25
Else
client.Port = Convert.ToInt32(port)
End If
client.Port = 25
client.Host = "smtp.gmail.com"
client.EnableSsl = True
client.Timeout = 180000
client.Send(mail)
SendMail = True
mail.Dispose()
Catch ex As Exception
WriteLog(ex.ToString(), EventLogEntryType.Error)
SendMail = False
End Try
End Function

''' <summary>
''' Get User Detail from the Sql
''' </summary>
''' <remarks>Created By Amit Patel</remarks>
Private Function getResult1() As String
Try

Dim con As New SqlConnection("Data Source=Amit\SQLEXPRESS;Initial Catalog=UserCreation;User Id=sarkar;Password=sarkar;")
Dim cmd As New SqlCommand()
con.Open()
cmd.Connection = con
cmd.CommandText = "select FirstName from rraannaammeett where UserId = 4"
cmd.CommandType = CommandType.Text
Dim da As New SqlDataAdapter()
Dim dt1 As New DataTable()
da.SelectCommand = cmd
da.Fill(dt1)
NewName = Convert.ToString(dt1.Rows(0)(0))
con.Close()
Dim result1 As String
result1 = NewName
Return result1
Catch ex As Exception
WriteLog(ex.ToString(), EventLogEntryType.Error)
Return 0
End Try
End Function

#End Region
End Class

After this code make service exe and install in your system and start it.

OutPut
Dear Ranna,

User Processing Status at 08:00 AM of 12-Oct-2012,

User Name             :  Ranna Patel

Thanks & Regards
Amit Patel
Software Developer | Baroda | India.
Ext.- 9033323299