Click here to Skip to main content
15,891,033 members
Articles / Programming Languages / C#

C# Script: The Missing Puzzle Piece

Rate me:
Please Sign up or sign in to vote.
4.88/5 (184 votes)
6 Aug 2014MIT24 min read 1.3M   9.4K   531  
An article on a "scripting engine" for the C# language
using System;
using System.Windows.Forms;
using System.Web;
using System.IO;
using System.Web.Mail;

namespace CSScript
{
	class Script
	{
		const string usage = "Usage: smtpmailto.cs smtpServer to subject body [file0] [fileN] ...\nSends e-mail to the specified address (use \"\" for local smtp server)\n";
		//"" user@domain "just a test" "was sent by script"

		static public void Main(string[] args)
		{
			if (args.Length < 4 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
			{
				Console.WriteLine(usage);
			}
			else
			{
				try
				{
					string server = args[0];
					string to = args[1];
					string subject = args[2];
					string body = args[3];
					string[] attachments = null;
					if (args.Length > 4)
					{
						attachments = new string[args.Length - 4];
						for (int i = 0; i < attachments.Length; i++)
						{
							attachments[i] = args[4 + i];
						}
					}
	
					MailMessage myMail = new MailMessage();
					myMail.To = to;
					myMail.Subject = subject;
					myMail.Body = body;
					if (attachments != null)
					{
						
						foreach (string file in attachments)
						{
							if (File.Exists(file))
							{
								string filePath = Path.GetFullPath(file);
								myMail.Attachments.Add(new MailAttachment(filePath, MailEncoding.Base64));
							}
							else
								throw new Exception("File "+file+" cannot be attached");
						}
					}
	
					SmtpMail.SmtpServer = server;
					SmtpMail.Send(myMail);
				}
				catch(Exception e)
				{
					Console.WriteLine(e);
					return;
				}

				Console.WriteLine("Message has been sent");
			}
		}
	}

}

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, along with any associated source code and files, is licensed under The MIT License


Written By
Program Manager
Australia Australia
I was born in Ukraine. After completing the university degree worked there as a Research Chemist. Last 23 years I live in Australia where I've got my second qualification as a Software Engineer.

"I am the lucky one: I do enjoy what I am doing!"

Comments and Discussions