Wednesday, January 14, 2009

Free code! Send email from your Exchage account - programmatically!

Note: This requires Exchange 2007.

In Visual Studio 2008, create a Visual C# Console application project. Call it SendMail for simplicity.

References->Add Service Reference->Advanced->Add Web Reference

In URL box, put a server name on which you have an account. The format of the URL should be something like this https://mail.microsoft.com/EWS/Exchange.asmx


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

using SendMail.com.microsoft.mail;

namespace SendMail
{
class Program
{
/// <summary>
/// Shows usage.
/// </summary>
private static void DisplayUsage()
{
Console.WriteLine("Usage:\n");
Console.WriteLine(" sendmail [--to emailaddress]+\n");
Console.WriteLine(" [--cc emailaddress]*\n");
Console.WriteLine(" [--from emailaddress]?\n");
Console.WriteLine(" [--subject textlineinquotes]?\n");
Console.WriteLine(" [--user username]\n");
Console.WriteLine(" [--domain domain]?\n");
Console.WriteLine(" [--password password]\n");
Console.WriteLine(" [--ews exchangewebserviceurl]\n");
Console.WriteLine(" Text to send in email\n");
Console.WriteLine("+ = one or more, * = zero or more, ? = zero or one");
Console.WriteLine("Note: username and password are required.");
}

/// <summary>
/// Processes command line args, sends one email.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string user = null;
string password = null;
string domain = null;
string ews = null;
List<string> to = new List<string>();
List<string> cc = new List<string>();
string from = null;
string subject = null;
StringBuilder text = new StringBuilder();
for (int i = 0; i < args.Length; ++i)
{
if (i < args.Length - 1)
{
if (args[i].Equals(
"--user", StringComparison.InvariantCultureIgnoreCase))
{
user = args[++i];
continue;
}
if (args[i].Equals(
"--domain", StringComparison.InvariantCultureIgnoreCase))
{
domain = args[++i];
continue;
}
if (args[i].Equals(
"--password", StringComparison.InvariantCultureIgnoreCase))
{
password = args[++i];
continue;
}
if (args[i].Equals(
"--ews", StringComparison.InvariantCultureIgnoreCase))
{
ews = args[++i];
continue;
}
if (args[i].Equals(
"--to", StringComparison.InvariantCultureIgnoreCase))
{
to.Add(args[++i]);
continue;
}
if (args[i].Equals(
"--cc", StringComparison.InvariantCultureIgnoreCase))
{
cc.Add(args[++i]);
continue;
}
if (args[i].Equals(
"--from", StringComparison.InvariantCultureIgnoreCase))
{
from = args[++i];
continue;
}
if (args[i].Equals(
"--subject", StringComparison.InvariantCultureIgnoreCase))
{
subject = args[++i];
continue;
}
}

if (text.Length > 0)
text.Append(" ");

text.Append(args[i]);
}

if (to.Count == 0 || user == null || password == null || ews == null)
{
DisplayUsage();
return;
}

ExchangeServiceBinding binding = new ExchangeServiceBinding();
binding.Credentials = new NetworkCredential(user, password, domain);
binding.Url = ews;

DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.sentitems;

TargetFolderIdType targetFolder = new TargetFolderIdType();
targetFolder.Item = folder;

CreateItemType createItem = new CreateItemType();
createItem.MessageDisposition = MessageDispositionType.SendAndSaveCopy;
createItem.MessageDispositionSpecified = true;
createItem.SavedItemFolderId = targetFolder;

MessageType message = new MessageType();

List<EmailAddressType> recipients = new List<EmailAddressType>();
foreach (string s in to)
{
EmailAddressType recipient = new EmailAddressType();
recipient.EmailAddress = s;
recipients.Add(recipient);
}

message.ToRecipients = recipients.ToArray();

if (cc.Count > 0)
{
recipients = new List<EmailAddressType>();
foreach (string s in cc)
{
EmailAddressType recipient = new EmailAddressType();
recipient.EmailAddress = s;
recipients.Add(recipient);
}

message.CcRecipients = recipients.ToArray();
}

if (from != null)
{
message.From = new SingleRecipientType();
message.From.Item = new EmailAddressType();
message.From.Item.EmailAddress = from;
}

message.Subject = subject;
message.Sensitivity = SensitivityChoicesType.Normal;

message.Body = new BodyType();
message.Body.BodyType1 = BodyTypeType.Text;
message.Body.Value = text.ToString();

createItem.Items = new NonEmptyArrayOfAllItemsType();
createItem.Items.Items = new MessageType[1];
createItem.Items.Items[0] = message;

CreateItemResponseType response = binding.CreateItem(createItem);
foreach (ResponseMessageType r in response.ResponseMessages.Items)
{
if (r.ResponseClass == ResponseClassType.Success)
{
Console.WriteLine("Message sent.");
}
else
{
Console.WriteLine("Failed to send the message. ");
Console.WriteLine(r.MessageText);
}
}
}
}
}

2 comments:

Egor Pasko said...

What is your definition of freedom used in the title? As in beer?

Sergey Solyanik said...

Yes, as in beer :-).