Click here to Skip to main content
15,888,610 members
Articles / Programming Languages / C#

Command Line Emailer

Rate me:
Please Sign up or sign in to vote.
4.93/5 (34 votes)
24 Sep 20034 min read 153.7K   1.5K   78  
A console application for sending email from the command line
using System;
using System.IO;
using System.Web.Mail;
using System.Text;
using System.Collections;

namespace CommandLineEmailer
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class CommandLineEmailer
	{

		static string _smtpserver		= "";
		static string _from			    = "";
		static string _to				= "";
		static string _cc				= "";
		static string _bcc				= "";
		static string _subject			= "";
		static ArrayList _textblocks	= new ArrayList();
		static ArrayList _attachments	= new ArrayList();


		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			try 
			{
				Console.WriteLine("");

				// parse the command line
				CommandLineParser cp = new CommandLineParser(System.Environment.CommandLine);
					
				// if there were no arguments supplied, or the /? switch has been supplied, display usage
				if (args.Length == 0 || cp.HasSwitch("?"))
				{
					Console.WriteLine("Command Line Emailer - Sends SMTP email from the command line");
					Console.WriteLine("");
					Console.WriteLine("Usage:");
					Console.WriteLine("  CommandLineEmailer [/p:parameterFile] [/smtp:smtpserver] [/f:from]");
					Console.WriteLine("                     [/to:recipients] [/cc:courtesyCopies]");
					Console.WriteLine("                     [/bcc:blindCourtesyCopies] [/s:subject] [/b:body]");
					Console.WriteLine("                     [/a:attachment] [/i:insertFile] [/?] ");
					Console.WriteLine("");
					Console.WriteLine("Switches:");
					Console.WriteLine("  /p:     parameter file; file containing message parameters");
					Console.WriteLine("          If a parameter file is not present, then required values must be");
					Console.WriteLine("          indicated through other switches.");
					Console.WriteLine("");
					Console.WriteLine("  /smtp:  Smtp server (overrides smtpserver= value in parameterFile if ");
					Console.WriteLine("          both are present)");
					Console.WriteLine("");
					Console.WriteLine("  /f:     message sender (overrides from= value in parameterFile if both ");
					Console.WriteLine("          are present)");
					Console.WriteLine("");
					Console.WriteLine("  /to:    semicolon-delimited list of message recipients (overrides ");
					Console.WriteLine("          to= value in parameterFile if both are present)");
					Console.WriteLine("");
					Console.WriteLine("  /cc:    semicolon-delimited list of message courtesy-copy recipients ");
					Console.WriteLine("          (overrides cc= value in parameterFile if both are present)");
					Console.WriteLine("");
					Console.WriteLine("  /bcc:   semicolon-delimited list of message blind courtesy-copy recipients");
					Console.WriteLine("          (overrides bcc= value in parameterFile if both are present)");
					Console.WriteLine("");
					Console.WriteLine("  /s:     message subject (overrides subject= value in parameterFile if ");
					Console.WriteLine("          both are present)");
					Console.WriteLine("");
					Console.WriteLine("  /b:     message body (adds to any body= value in parameterFile if both");
					Console.WriteLine("          are present)");
					Console.WriteLine("");
					Console.WriteLine("  /a:     file attachment (adds to any attachment= value in parameterFile if ");
					Console.WriteLine("          both are present)");
					Console.WriteLine("");
					Console.WriteLine("  /i:     insert the supplied text file in the body (adds to any ");
					Console.WriteLine("          insertfile= value in parameterFile if both are present)");
					Console.WriteLine("");
					Console.WriteLine("  /?      display this help text");
					Console.WriteLine("");
					Console.WriteLine("Notes:");
					Console.WriteLine("  The parameter file is a text file with lines in the following format:");
					Console.WriteLine("");
					Console.WriteLine("      key=value");
					Console.WriteLine("");
					Console.WriteLine("  The following example shows how each key may be used.");
					Console.WriteLine("");
					Console.WriteLine("      smtpserver = MySmtpServer.Com");
					Console.WriteLine("      from       = sender@mycompany.com");
					Console.WriteLine("      to         = recipient@mycompany.com; recipient2@mycompany.com");
					Console.WriteLine("      cc         = cc1@mycompany.com");
					Console.WriteLine("      bcc        = bcc1@mycompany.com");
					Console.WriteLine("      subject    = This is the message subject");
					Console.WriteLine("      body       = This is line 1 of the message body");
					Console.WriteLine("      body       = This is line 2 of the message body");
					Console.WriteLine("      attachment = FirstAttachment.doc");
					Console.WriteLine("      attachment = SecondAttachment.doc");
					Console.WriteLine("      insertfile = InsertThisFirstFileIntoBody.txt");
					Console.WriteLine("      insertfile = InsertThisSecondFileIntoBodyAlso.txt");
					Console.WriteLine("");
				} 
				else 
				{
					// if a parameter file has been supplied, process it first
					if (cp.HasSwitch("p")) ProcessParameterFile(cp.SwitchValue("p"));

					// then process any other switches that may override values or add to values
					
					// /smtp:SmtpServer?
					if (cp.HasSwitch("smtp")) _smtpserver = cp.SwitchValue("smtp");
					// /f:From?
					if (cp.HasSwitch("f")) _from = cp.SwitchValue("f");
					// /to:To?
					if (cp.HasSwitch("to")) _to = cp.SwitchValue("to");
					// /cc:Cc?
					if (cp.HasSwitch("cc")) _cc = cp.SwitchValue("cc");
					// /bcc:Bcc?					
					if (cp.HasSwitch("bcc")) _bcc = cp.SwitchValue("bcc");
					// /s:subject?
					if (cp.HasSwitch("s")) _subject = cp.SwitchValue("s");
					// /b:Body?
					if (cp.HasSwitch("b")) _textblocks.Add(cp.SwitchValue("b"));
					// /a:Attachment?
					if (cp.HasSwitch("a")) _attachments.Add(cp.SwitchValue("a"));
					// /i:Insert file?
					if (cp.HasSwitch("i")) 
					{
						string val = cp.SwitchValue("i");
						try 
						{
							_textblocks.Add(LoadTextFile(val)); 
						} 
						catch (Exception ex) 
						{
							_textblocks.Add("<Error inserting text file " + val + ": " + ex.Message + ">");
						}
					}


					// any required values missing?
					if (_smtpserver == "")
						Console.WriteLine("SmtpServer is required, either in a /p:ParameterFile or /smtp: switch");
					else if(_from == "")
						Console.WriteLine("From is required, either in a /p:ParameterFile or /f: switch");
					else if (_to == "")
						Console.WriteLine("To is required, either in a /p:ParameterFile or /to: switch");
					else 
					{
						// generate and send an email message
						SendEmailMessage();
						Console.WriteLine("Mail sent.");
					}
				}

			}
			catch (Exception ex) 
			{
				Console.WriteLine("");
				Console.WriteLine(ex.ToString());
				Console.WriteLine("");
			}

			//Console.WriteLine("");
			//Console.WriteLine("Press Enter to Continue...");
			//Console.ReadLine();
				
		}

		/// <summary>
		/// Open the parameter file, parse it, and send the email
		/// </summary>
		public static void ProcessParameterFile(string parameterFile)
		{
			// open and read the file
			String contents = LoadTextFile(parameterFile);
            
			// parse the contents to an array of lines
			string[] lines = GetLinesFromString(contents);
			
			// loop through each line to establish our configuration
			for (int i=0; i<lines.Length; i++) 
			{
				ParseLine(lines[i]);
			}

		}

		/// <summary>
		/// given a string of text lines (\n delimited) return an array of individual string lines
		/// </summary>
		public static string[] GetLinesFromString(string contents)
		{
			return contents.Split('\n');
			//return contents.Split(System.Environment.NewLine);
		}


		/// <summary>
		/// parse a line in the form key=value
		/// </summary>
		public static void ParseLine(string line)
		{
			string[] a = line.Split('=');
			string key = (a.Length == 0 ? "" : a[0].Trim());
			string val = (a.Length == 1 ? "" : a[1].Trim());

			switch (key.ToLower()) 
			{
				case "smtpserver" : _smtpserver = val;	break;
				case "from"		  : _from = val;		break;
				case "to"		  : _to = val;			break;
				case "cc"		  : _cc = val;			break;
				case "bcc"		  :	_bcc = val;			break;
				case "subject"	  : _subject = val;		break;
				case "body"		  : _textblocks.Add(val); break;
				case "attachment" :	_attachments.Add(val); break;
				case "insertfile" : 
					try 
					{
						_textblocks.Add(LoadTextFile(val)); 
					} 
					catch (Exception ex) 
					{
						_textblocks.Add("<Error inserting text file " + val + ": " + ex.Message + ">");
					}
					break;
					
					// everything else is ignored;
			}

		}

		/// <summary>
		/// generate and send the email message
		/// </summary>
		public static void SendEmailMessage() 
		{
			SmtpMail.SmtpServer = _smtpserver;
			MailMessage mm = new MailMessage();
			mm.From = _from;
			mm.To = _to;
			mm.Cc = _cc;
			mm.Bcc = _bcc;
			mm.Subject = _subject;

			// add all textblocks to the body
			StringBuilder sb = new StringBuilder();
			foreach(string s in _textblocks) 
			{
				sb.Append(s + System.Environment.NewLine);
			}
			mm.Body = sb.ToString() + System.Environment.NewLine;

			
			// attempt to add any attachments; on an error here, add error text to the body
			foreach(string s in _attachments) 
			{
				try 
				{
					string fullPath = System.IO.Path.GetFullPath(s);
					mm.Attachments.Add(new MailAttachment(fullPath));
				}
				catch (Exception ex) 
				{
					mm.Body += System.Environment.NewLine;
					mm.Body += "<Error attaching file " + s + ": " + ex.Message + ">";
					mm.Body += System.Environment.NewLine;
				}
			}

			SmtpMail.Send(mm);
		}

		/// <summary>
		/// load a text file and return its contents as a string
		/// </summary>
		public static string LoadTextFile(string f) {
			FileStream fs = File.OpenRead(f);
			StreamReader sr = new StreamReader(fs);
			String contents = sr.ReadToEnd();
			sr.Close();
			fs.Close();
			return contents;
		}


	}


}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
University of Nevada, Las Vegas
United States United States
With a background in education, music, application development, institutional research, data governance, and business intelligence, I work for the University of Nevada, Las Vegas helping to derive useful information from institutional data. It's an old picture, but one of my favorites.

Comments and Discussions