locked
Automatic Email alert generation RRS feed

  • Question

  • User2072898193 posted

    hi.. my web application contain insurance due date field(in TextBox,which is enterd by user),and i need automatic email alert generation for this field 1 month before the date specified in the textbox to specific email address... how can i code my requirement in c#...can any one one suggest altenate option if my concept is wrong...thanks in advance 

    Tuesday, September 7, 2010 11:34 PM

Answers

  • User-1558584061 posted

    This is all u would need, i took it from some site but dont remember it now. Worth going through :)

    This article explain how to send mail automatically using window service, Concepts are involved for sending mail automatically are SMTP Server for sending mails, Window service used to mail automatically, Event log is used to see whether the window service is working, below explain detail.

     

    1. Window Service

    2. Event Log

    3. SMTP Client

    4. Timer Concepts

    5. Steps to Create Automatic Mail Service

    6. Create Windows Service Deployment project

    7. Instal and Un-install the windows servie project

    8. Start and Stop your service

    9. View your log files

     

    1.Window Service

     

    Windows Service is used to create a application to run in a windows sessions. windows service can automatically run,  restart or paused when the system boots , we do not show any user interface for doing the window service.

     

    In .Net framework support two type of windows service. window service can run in a single process to be create in Win32ownprocess and the service can share the process to be create in win32shareprocess. we can retrieve the information of the process using servicetype property.

     

    They are two overrides method are used to Start and Stop your windows service.

     

    1. Start  method

     

    protected override void OnStart(string[] args)
    {
       //Your coding

    }

    2. Stop Method

    protected override void OnStart(string[] args)
    {
       //Your coding

    }

     

     


     

    2.Event Log

    Eventlog class used to create or accessing the windows event logs. Administration privileges need to write to an event log for every logs.EventLog,class method are used to read from existing logs, write entries to logs and create a logs  or delete event sources.

    Check whether event log exisits in system using SourceExists method, if not created already create eventlog using CreateEventSource method and write to the event Source

     

    Examples:

     

     Create New EventLog

    if(EventLog.SourceExists("AutoMail"))

    {

             EventLog.CreateEventSource("AutoMail","Mails");

    }

     

    Write the information in existing logs

    eventLog1.Source="AutoMail";
    eventLog1.Log = "Mails";

     

    3.SMTP Server

    The SMTP Server Class is used to Send Mail from a SMTP Server. .Net Framework 2.0 later supports the SMTP Server class from  System.Net.Mail namespace. 

     

    It System.Net.Mail namespace supports three class

     

    a) MailMessage

    b) MailAddress.and

    c) Attachments

     

    Mail Message is used to describe the messages.

    Mail Address is used to define theh sender and recipiants.

    Attachments is used to attach the file along with the mail.

     

    Examples:

    MailMessage mailMsg = new MailMessage();

    MailAddress mailAddress = null;

    mailMsg.To.Add(tmuhilan@gmail.com);

     

    mailAddress =new MailAddress(Muhilan@maa.com.my);

     

    mailMsg.From = mailAddress;

    mailMsg.Subject = "Automatic mailing";

    mailMsg.Body = "Tomorrow Meeting at 6.30PM";

     

    SmtpClient smtpClient = new SmtpClient("97.0.0.6", Convert.ToInt32(25));

    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();

    smtpClient.Credentials = credentials;

     

    smtpClient.Send(mailMsg);

    Here i have used  ipaddress and Port number is our SMTP server. So change the ip and port according to your SMTP Server configuration.

     

     

    4. Timer Concepts

    .Net providers timer component is a server-based timer allows you to specify interval and the elapsed event is raised in your application. This event to provide regular processing. while create a service that uses a timer to periodically , it will check the server is running or not.

    While service could attempt to restart the server, timer component raises the elapsed event based on the value of the interval property.

    Examples:

     

    System.Timers.Timer time = new System.Timers.Timer();

    time.Start();

    time.Interval = 300000;

    time.Elapsed += time_elapsed;

         

    public void time_elapsed(object sender, ElapsedEventArgs e)

    {


    }

     

    5.   Steps

    1. Create New Project under Visual Studio -> File -> New -> Project -> Select Project Types -> Visual C# and choose windows service
    2. Change Service name as per your naming standard
    3. From Toolbox -> Components ->Select Eventlog component. Drag the Eventlog component and drop in design.
    4. Rightclick and choose view code , In constructor check whether the event log exists or not , if not exists create the event log.
    5. Examples:

    if (!System.Diagnostics.EventLog.SourceExists("MailSend"))

    {

    System.Diagnostics.EventLog.CreateEventSource(

    "MailSend", "AutoMailLog");

    }

    MyLogEvent.Source = "MailSend";

    MyLogEvent.Log = "AutoMailLog";

        6.  Next onStart Override method

    Here , create timer component and assign the interval values and other properties

    MyLogEvent.WriteEntry("In OnStart --- Sending Mail to" + Dt);

    System.Timers.Timer time = new System.Timers.Timer();

    time.Start();

    time.Interval = 300000;

    time.Elapsed += time_elapsed;


    time_elapsed event to be call for every 5 minutes 

    public void time_elapsed(object sender, ElapsedEventArgs e)

    {

    MyLogEvent.WriteEntry("Mail Sending on " + DateTime.Now.ToString());

    SendEmail("Muhilan@maa.com.my", "tmuhilan@gmail.com", "Automatic Mail sending", "Successfully working contact tmuhilan@gmail.com");

    }

     

    7.  Here SendEmail is my function for sending mail

    public bool SendEmail(string strTo, string strFrom, string strSubject, string strBody)

    {

    bool flag = false;

    MailMessage mailMsg = new MailMessage();

    MailAddress mailAddress = null;

    try

    {

    // To

    mailMsg.To.Add(strTo);

    mailAddress = new MailAddress(strFrom);

    mailMsg.From = mailAddress;

    mailMsg.Subject = strSubject;

    mailMsg.Body = strBody;

    SmtpClient smtpClient = new SmtpClient("97.0.0.6", Convert.ToInt32(25));

    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();

    smtpClient.Credentials = credentials;

    smtpClient.Send(mailMsg);

    flag = true;

    MyLogEvent.WriteEntry("Mail Send Successfully");

    }

    catch (Exception ex)

    {

    MyLogEvent.WriteEntry("Error occured");

    //Response.Write(ex.Message);

    }

    finally

    {

    mailMsg = null;

    mailAddress = null;

    }

    return flag;

    }

    8. Once written coding , compile if no error occurs. Then

    9. Rightclick in design mode ->Select Add installer -> it will create two components

    a) ServiceProcessInstaller and b) ServiceInstaller

    a) ServiceProcessInstaller is used to define the windows service work in which account.Here we can set the account type as LocalSystem , User,Network service. In my project i have used LocalSystem.

    b)ServiceInstaller Set ServiceName as anything(AutoMail) and Starttype as Automatic

    10. Once Set the property and Build. Now created web service.

    6. Create windows service depolyment project

    1.  In solution explorer, Add new project -> select setup and deployment under other project types
    2. Right click the project -> Add -> Project Output
    3. In a project item for the primary output of your service is added to the setup project.
    4. Now to add a custom action to install the service.exe file.

        5.  In Solution Explorer, right-click the setup project -> point to View -> then choose Custom Actions.

            The Custom Actions editor appears.

    1. In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action.

    The Select Item in Project dialog box appears.

    1. Double-click the Application Folder in the list box to open it, select Primary Output from Service (Active), and click OK.

    The primary output is added to all four nodes of the custom actions 

    1.  Install, Commit, Rollback, and Uninstall.
    2. In Solution Explorer, right-click the ServiceSetup project and choose Build.

    7. To install the Windows Service

          To install service.exe, right-click the setup project in the Solution Explorer and select Install.If you want to unistall your service , right-click the sertup project in the solution explorer and select uninstall options.

    8. Stop and Start your service

    1. For Xp windows-> click Start, point to Programs-> My Computer -> rightclick-> then select Manage

    2. Computer Management Consle windows will appear

    3. Select the Service and Applications node , in the sub node select services , there

            4.  Select your service in the list, right-click it, and then click Start.

            5.   Right-click the service, and then click Stop.

     

    9. View your event log files

    1. For Xp windows-> click Start, point to Programs-> My Computer -> rightclick-> then select Manage

    2. Computer Management Consle windows will appear

    3. select the System Tools node , in the sub node select Event Viewer

    4. Select your event log from the list, in the right side panel you can see the event logs trigger based on your coding

      

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 8, 2010 1:41 AM

All replies

  • User-1802908944 posted

    for this you need to use Scheduler window service. and you need to check the date of record before month month. if date matched then you need to send a mail with alert.

    if you have any idea. then let me know. i will let you know.

    or mail me



    Wednesday, September 8, 2010 12:08 AM
  • User2072898193 posted

    bt how can i code to generate automatic email alert for records which is already inserted in database,Everyday i need to validate whether current system date is a month before insurance due date of records in database,if database having such records then an email alert will generatad to a specific address 

    Wednesday, September 8, 2010 12:52 AM
  • Wednesday, September 8, 2010 1:15 AM
  • User-1558584061 posted

    This is all u would need, i took it from some site but dont remember it now. Worth going through :)

    This article explain how to send mail automatically using window service, Concepts are involved for sending mail automatically are SMTP Server for sending mails, Window service used to mail automatically, Event log is used to see whether the window service is working, below explain detail.

     

    1. Window Service

    2. Event Log

    3. SMTP Client

    4. Timer Concepts

    5. Steps to Create Automatic Mail Service

    6. Create Windows Service Deployment project

    7. Instal and Un-install the windows servie project

    8. Start and Stop your service

    9. View your log files

     

    1.Window Service

     

    Windows Service is used to create a application to run in a windows sessions. windows service can automatically run,  restart or paused when the system boots , we do not show any user interface for doing the window service.

     

    In .Net framework support two type of windows service. window service can run in a single process to be create in Win32ownprocess and the service can share the process to be create in win32shareprocess. we can retrieve the information of the process using servicetype property.

     

    They are two overrides method are used to Start and Stop your windows service.

     

    1. Start  method

     

    protected override void OnStart(string[] args)
    {
       //Your coding

    }

    2. Stop Method

    protected override void OnStart(string[] args)
    {
       //Your coding

    }

     

     


     

    2.Event Log

    Eventlog class used to create or accessing the windows event logs. Administration privileges need to write to an event log for every logs.EventLog,class method are used to read from existing logs, write entries to logs and create a logs  or delete event sources.

    Check whether event log exisits in system using SourceExists method, if not created already create eventlog using CreateEventSource method and write to the event Source

     

    Examples:

     

     Create New EventLog

    if(EventLog.SourceExists("AutoMail"))

    {

             EventLog.CreateEventSource("AutoMail","Mails");

    }

     

    Write the information in existing logs

    eventLog1.Source="AutoMail";
    eventLog1.Log = "Mails";

     

    3.SMTP Server

    The SMTP Server Class is used to Send Mail from a SMTP Server. .Net Framework 2.0 later supports the SMTP Server class from  System.Net.Mail namespace. 

     

    It System.Net.Mail namespace supports three class

     

    a) MailMessage

    b) MailAddress.and

    c) Attachments

     

    Mail Message is used to describe the messages.

    Mail Address is used to define theh sender and recipiants.

    Attachments is used to attach the file along with the mail.

     

    Examples:

    MailMessage mailMsg = new MailMessage();

    MailAddress mailAddress = null;

    mailMsg.To.Add(tmuhilan@gmail.com);

     

    mailAddress =new MailAddress(Muhilan@maa.com.my);

     

    mailMsg.From = mailAddress;

    mailMsg.Subject = "Automatic mailing";

    mailMsg.Body = "Tomorrow Meeting at 6.30PM";

     

    SmtpClient smtpClient = new SmtpClient("97.0.0.6", Convert.ToInt32(25));

    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();

    smtpClient.Credentials = credentials;

     

    smtpClient.Send(mailMsg);

    Here i have used  ipaddress and Port number is our SMTP server. So change the ip and port according to your SMTP Server configuration.

     

     

    4. Timer Concepts

    .Net providers timer component is a server-based timer allows you to specify interval and the elapsed event is raised in your application. This event to provide regular processing. while create a service that uses a timer to periodically , it will check the server is running or not.

    While service could attempt to restart the server, timer component raises the elapsed event based on the value of the interval property.

    Examples:

     

    System.Timers.Timer time = new System.Timers.Timer();

    time.Start();

    time.Interval = 300000;

    time.Elapsed += time_elapsed;

         

    public void time_elapsed(object sender, ElapsedEventArgs e)

    {


    }

     

    5.   Steps

    1. Create New Project under Visual Studio -> File -> New -> Project -> Select Project Types -> Visual C# and choose windows service
    2. Change Service name as per your naming standard
    3. From Toolbox -> Components ->Select Eventlog component. Drag the Eventlog component and drop in design.
    4. Rightclick and choose view code , In constructor check whether the event log exists or not , if not exists create the event log.
    5. Examples:

    if (!System.Diagnostics.EventLog.SourceExists("MailSend"))

    {

    System.Diagnostics.EventLog.CreateEventSource(

    "MailSend", "AutoMailLog");

    }

    MyLogEvent.Source = "MailSend";

    MyLogEvent.Log = "AutoMailLog";

        6.  Next onStart Override method

    Here , create timer component and assign the interval values and other properties

    MyLogEvent.WriteEntry("In OnStart --- Sending Mail to" + Dt);

    System.Timers.Timer time = new System.Timers.Timer();

    time.Start();

    time.Interval = 300000;

    time.Elapsed += time_elapsed;


    time_elapsed event to be call for every 5 minutes 

    public void time_elapsed(object sender, ElapsedEventArgs e)

    {

    MyLogEvent.WriteEntry("Mail Sending on " + DateTime.Now.ToString());

    SendEmail("Muhilan@maa.com.my", "tmuhilan@gmail.com", "Automatic Mail sending", "Successfully working contact tmuhilan@gmail.com");

    }

     

    7.  Here SendEmail is my function for sending mail

    public bool SendEmail(string strTo, string strFrom, string strSubject, string strBody)

    {

    bool flag = false;

    MailMessage mailMsg = new MailMessage();

    MailAddress mailAddress = null;

    try

    {

    // To

    mailMsg.To.Add(strTo);

    mailAddress = new MailAddress(strFrom);

    mailMsg.From = mailAddress;

    mailMsg.Subject = strSubject;

    mailMsg.Body = strBody;

    SmtpClient smtpClient = new SmtpClient("97.0.0.6", Convert.ToInt32(25));

    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();

    smtpClient.Credentials = credentials;

    smtpClient.Send(mailMsg);

    flag = true;

    MyLogEvent.WriteEntry("Mail Send Successfully");

    }

    catch (Exception ex)

    {

    MyLogEvent.WriteEntry("Error occured");

    //Response.Write(ex.Message);

    }

    finally

    {

    mailMsg = null;

    mailAddress = null;

    }

    return flag;

    }

    8. Once written coding , compile if no error occurs. Then

    9. Rightclick in design mode ->Select Add installer -> it will create two components

    a) ServiceProcessInstaller and b) ServiceInstaller

    a) ServiceProcessInstaller is used to define the windows service work in which account.Here we can set the account type as LocalSystem , User,Network service. In my project i have used LocalSystem.

    b)ServiceInstaller Set ServiceName as anything(AutoMail) and Starttype as Automatic

    10. Once Set the property and Build. Now created web service.

    6. Create windows service depolyment project

    1.  In solution explorer, Add new project -> select setup and deployment under other project types
    2. Right click the project -> Add -> Project Output
    3. In a project item for the primary output of your service is added to the setup project.
    4. Now to add a custom action to install the service.exe file.

        5.  In Solution Explorer, right-click the setup project -> point to View -> then choose Custom Actions.

            The Custom Actions editor appears.

    1. In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action.

    The Select Item in Project dialog box appears.

    1. Double-click the Application Folder in the list box to open it, select Primary Output from Service (Active), and click OK.

    The primary output is added to all four nodes of the custom actions 

    1.  Install, Commit, Rollback, and Uninstall.
    2. In Solution Explorer, right-click the ServiceSetup project and choose Build.

    7. To install the Windows Service

          To install service.exe, right-click the setup project in the Solution Explorer and select Install.If you want to unistall your service , right-click the sertup project in the solution explorer and select uninstall options.

    8. Stop and Start your service

    1. For Xp windows-> click Start, point to Programs-> My Computer -> rightclick-> then select Manage

    2. Computer Management Consle windows will appear

    3. Select the Service and Applications node , in the sub node select services , there

            4.  Select your service in the list, right-click it, and then click Start.

            5.   Right-click the service, and then click Stop.

     

    9. View your event log files

    1. For Xp windows-> click Start, point to Programs-> My Computer -> rightclick-> then select Manage

    2. Computer Management Consle windows will appear

    3. select the System Tools node , in the sub node select Event Viewer

    4. Select your event log from the list, in the right side panel you can see the event logs trigger based on your coding

      

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 8, 2010 1:41 AM
  • User-1558584061 posted

    Hey, any updates on ur problems are appreciated. So do tell us if u have sorted it out and how?

    Tuesday, September 14, 2010 6:06 AM
  • User-952121411 posted

    i need automatic email alert generation for this field 1 month before the date specified in the textbox to specific email address... how can i code my requirement in c#...
     

    It sounds like you have the 1st part complete; get a record in the database with the due date that can be checked periodically.  This is where the solution comes in to play.

    You need to create a Windows Service (designed for long running tasks, like polling of data on interval), and have it poll on any interval you want (second, minute, hour, daily, weekly, whatever).  Upon having the timer or event elapse, you need to make a call out to your database to get all of the due dates within range.  Once you have the records back (all due dates out 1 month or whatever) you can send emails directly from your Windows Service.

    Take a look at the following article which has links for code examples and setting up and installing your Windows Service from scratch:

    Running a Periodic Process in .NET using a Windows Service:

    http://allen-conway-dotnet.blogspot.com/2009/12/running-periodic-process-in-net-using.html

    Tuesday, September 14, 2010 9:04 AM
  • User-389939489 posted

    bt how can i code to generate automatic email alert for records which is already inserted in database,Everyday i need to validate whether current system date is a month before insurance due date of records in database,if database having such records then an email alert will generatad to a specific address 

     

    Assuming Sql Server, a relatively easy option is to write a stored procedure that does the job of sending out the needed emails (look for Database Mail) and updates the database, then you can schedule a job to execute the stored procedure.

    This solution gets cumbersome in case you need to generate and attach files to the email...

    HTH,

    -LV

    Tuesday, September 14, 2010 10:34 AM
  • User-952121411 posted

    This solution gets cumbersome in case you need to generate and attach files to the email...
     

    Not really it is quite trivial for most developers. All you need to do is read your file into a byte array (i.e. File.ReadAllBytes()) and then load the byte array into an Attachment object that can be added to the System.Net.Mail.MailMessage being created. Doing this on the server in a service is really easy to implement with a few lines of code. So if you have generated a bill and want to attach it, everything you need to build up that email and send it with an attachment will be in the System.IO and System.Net namespaces.

    Creating the bill is not difficult either.  Create an Adobe Form file as a template for a bill, and then merge db data into it using a tool like DynamicPDF or iText which both have simple to follow APIs.

    Tuesday, September 14, 2010 3:42 PM
  • User1080785583 posted

    I would think SSRS(SQL Server Reporting Services) would be able to handle this. 

    Tuesday, September 14, 2010 4:07 PM
  • User-389939489 posted

    >> This solution gets cumbersome in case you need to generate and attach files to the email...

    atconway:> Not really it is quite trivial for most developers.

    Maybe trivial for most developers: you have managed to miss that the solution in question is about a stored procedure.

    xequence:> I would think SSRS(SQL Server Reporting Services) would be able to handle this.

    Yes, otherwise there is CLR integration. But if you need to send out simple emails, Database Mail is quite enough.

    -LV

    Tuesday, September 14, 2010 5:34 PM
  • User1480033891 posted

    Hi,

    Here's what you need to do:

    • Create a stored procedure to fetch records and send via email
    • Create a scheduled Job that runs the stored procedure.

    within your store procedure, you need to use the CLR to send the email. here is my example of CLR procedure you can use

    http://www.wmacosta.com/SendMailSQLServerCLR.aspx

    I hope this helps.

    Regards
    Wilmar

     

     

    Thursday, September 16, 2010 12:56 PM
  • User-389939489 posted

    Wilmar:

    > Here's what you need to do:

    That's more or less the solution I had proposed.

    What you don't mention in your article is that, to be able to send emails with System.Net.Mail, an assembly requires EXTERNAL_ACCESS permission on Sql Server 2008, and UNSAFE permission on Sql Server 2005. Which is one of the main reasons why Database Mail is preferable in case all you need is sending out simple emails.

    -LV

    Friday, September 17, 2010 9:38 AM
  • User-1765575637 posted

    This is good solution to use Windows Solution to send auto email alerts. But I face a problem with it. That is Deployment.

    I want to deploy this Windows Service on remote web server on my demain. But my domain hosting dont provide me option

    to deploy windows services. I looks expensive.

    Tuesday, November 2, 2010 9:50 AM
  • User1710729944 posted

    Does it need to be exactly a month before or is within a day or so good enough for you?

    If so, then I'd add an entry to a database table for pending emails with the date they should be sent.  I'd write a program that looks at this table and sends emails that should be sent before the current time, and then deletes them from this table.  I would run this program as a scheduled task.

    This will probably be easier than setting up a windows service or configuring SQL server to send emails.  You could get it to send yourself an email each time it runs (so if it stops you know and can start it again), and if it goes down for a day then customers will still get their email albeit a little late.

     

    Tuesday, November 2, 2010 1:32 PM