Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » C# » General » Downloads
 

C# Script: The Missing Puzzle Piece

By , 30 Sep 2009
 
using System;
using System.Windows.Forms;
using System.Web;
using System.IO;
using System.Web.Mail;

namespace CSScript
{
	class Script
	{
		const string usage = "Usage: mailto.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.Message);
					return;
				}

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

}

By viewing downloads associated with this article you agree to the Terms of use 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 Code Project Open License (CPOL)

About the Author

Oleg Shilo
Technical Lead
Australia Australia
Member
I was born in Ukraine. After completing the university degree worked there as a chemist. Last 16 years I live in Australia where I've got my second qualification as a programmer.
 
"I am the lucky one: I do enjoy what I am doing!"

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 30 Sep 2009
Article Copyright 2004 by Oleg Shilo
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid