Popular Posts

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;
timer1.Start();

}

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

}


public void SendEmail()
{

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

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("smtp.urs.com");
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;

client.Send(Mail);
}

No comments: