Saturday, July 19, 2008

Automatically Sending Email from Sql Table Through Windows Services

Here is the windows services Code sample for automatically sending emails from your sql table.

The example uses a Timer to fire the event automatically. The mail is sent when time elapses.

public System.Timers.Timer timer1;
protected override void OnStart(string[] args)

timer1.Enabled = true;


private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)


public void SendEmail()

conn = new SqlConnection(@"Server=;UID=sa;pwd=sa;Database=");
da = new SqlDataAdapter("select top 1 * from tbl_mail where status=0 order by MailIn_DT", conn);
ds = new DataSet();

if (ds != null)
DataRow dr = ds.Tables[0].Rows[0];
string MailTo = dr["To_Mail"].ToString();
string MailSubject = dr["Subject"].ToString();
string MailMessage = dr["Message"].ToString();

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("");
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("Userid", "Password");
client.EnableSsl = true;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
System.Net.Mail.MailMessage Mail = new System.Net.Mail.MailMessage("Userid", MailTo, MailSubject, MailMessage);
Mail.IsBodyHtml = true;


No comments: