This is a follow up to my last SMTP example that adds a new twist for a practical use of email from within an application. This program will retrieve a stock quote from a website and automatically forward it to an email at any frequency you would like. The functionality of this example is primitive, but this could easily be built into a full featured server that supported many customers with customized stock lists. This program also demonstrates the use of the .NET Timer object. The Timer object lets you define an event handler that will execute every time the Timer times out.
The Quoter class does the work of retrieving the quote from the web. The class has a method called GetQuote(string stock) that uses an HttpWebRequest object to connect to the site. The stock string parameter is appended to web address. The html returned by the web request is read in one line at a time and parsed to find the appropriate information. The Quote class also overrides the ToString() method to return a string representing the quote to embed as the body of the email message. The info is returned in a Quote object, which is a simple wrapper for the stock quote information The QuoteTest class is a simple demonstrator. It implements the Timer object and defines the event handler. The program then goes into an infinite do-nothing loop waiting for the Timer to time out. When the Timer times out, the event handler gets a new quote, formats an email message, and sends it. You will need to replace the parameters in the SMTPMailer constructor with your own appropriate smtp server name and your host name. This will continue until you Ctrl-C it. The frequency can be set by changing the Timer Interval property. In this example, it is set to 10 minutes.
Requires .NET SDK
How To Compile?
QuoteTest: csc /r:System.dll /r:System.Net.dll /r:System.IO.dll /r:System.Timers.dll /r:Quoter.dll /r:SMTPMailer.dll /r:message.dll QuoteTest.cs
Quoter: csc /r:System.dll /r:System.Net.dll /r:System.IO.dll /target:library quoter.cs
SMTPMailer: csc /r:System.Net.dll /r:System.IO.dll /r:message.dll /target:library SMTPMailer.cs
Message: csc /target:library Message.cs
Compile in this order: Message, SMTPMailer, Quoter, QuoteTest
public static void Main()
Timer tmr = new Timer();
tmr.Tick += new EventHandler(OnTimedEvent);
tmr.Enabled = true;
Console.WriteLine("Quote Test running...");
public static void OnTimedEvent(object source, EventArgs e)
Quoter qtr = new Quoter();
SMTPMailer mlr = new SMTPMailer("SMTP Server Name", "Host Name");
Message msg = new Message();
msg.From = email@example.com;
msg.To = firstname.lastname@example.org;
msg.Subject = "Quote for TWCUX";
Quote q = qtr.GetQuote("twcux");
msg.Body = q.ToString();
Console.WriteLine("Quote has been sent...");