Windows Sevice Email utility
Hi, I saw a post on the ASP.NET website that requires the following:
Word files with names of particular date are stored in folder at webserver(i.e name of word file should be a date like 2.20.2007) This word file name format is like: 10.20.2007.doc
One background service will run with the such that, file with name of particular date will be sent on the particular date with the email application for example file with name 2.20.2007 will be sent on 2.20.2007
I would like to share you my solution,
First, since this application is intended to work on the background without interacting with the user (Actually the user is just adding files to the folder ), this should involve a Windows Service Project.
We have to check files every day so if the file name is the same as the date of the day, then send it.
to check the file every day we should use a Timer object that accepts a delegate of the function to be repeated in our case the function should check the file name then if accepted send it.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Net.Mime;
using System.Net.Mail;
using System.Threading;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
TimerCallback SendMail;
public Service1()
{
InitializeComponent();
SendMail = new TimerCallback(Send);
}
protected override void OnStart(string[] args)
{ //check the folder first after 12 hours the every day.
Timer t = new Timer(SendMail);
t.Change(TimeSpan.FromHours (12), TimeSpan.FromDays(1));
} //the function to be called when the timer ticks
public void Send(object arg)
{
string folderName = @"\WordFiles\";
DirectoryInfo di = new DirectoryInfo(folderName);
FileInfo[] fi = di.GetFiles();
//check every file in the folder
for (int i = 0; i < fi.Length; i++)
{
if (CheckFile(fi[i].Name))
{ //if accepted send the file as attatchment
SendFile(fi[i]);
}
}
}
public bool CheckFile(string name)
{// if thr file name is of the format mm.dd.yyyy then it's accepted
if ((Convert.ToInt32(name.Split('.')[0]) == DateTime.Now.Month) && (Convert.ToInt32(name.Split('.')[1]) == DateTime.Now.Day) && (Convert.ToInt32(name.Split('.')[2]) == DateTime.Now.Year))
{
return true;
}
else
return false;
}
public void SendFile(FileInfo fi)
{
MailMessage m = new MailMessage();
Stream sr = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
m.Attachments.Add(new Attachment(sr, "WordFile.doc", MediaTypeNames.Application.Octet));
SmtpClient sc = new SmtpClient();
m.From = new MailAddress("developer85@hotmail.com");
m.To.Add("bashar_ge@hotmail.com");
sc.PickupDirectoryLocation = "localhost";
sc.Send(m);
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}