Source Code

namespace Mail2SMS

{

using FreebieSMS.SendSMS;

using Microsoft.VisualBasic;

using Microsoft.VisualBasic.CompilerServices;

using System;

using System.Collections;

using System.ComponentModel;

using System.Configuration;

using System.Diagnostics;

using System.Net;

using System.Net.Mail;

using System.Net.Sockets;

using System.Runtime.CompilerServices;

using System.ServiceProcess;

using System.Text;

using System.Text.RegularExpressions;

using System.Threading;

using System.Timers;

using System.Web.Mail;

using System.Xml;

using ReadyPOP3;

[DesignerGenerated]

public class Srvc_Mail2SMS : ServiceBase

{

private static ArrayList __ENCList = new ArrayList();

[AccessedThroughProperty("EventLog1")]

private EventLog _EventLog1;

private IContainer components;

private string Country;

private System.Timers.Timer Timer1;

private sendSms Webservices4sendingSMS;

private string website;

public Srvc_Mail2SMS()

{

ArrayList list = __ENCList;

lock (list)

{

__ENCList.Add(new WeakReference(this));

}

this.Timer1 = new System.Timers.Timer();

this.Webservices4sendingSMS = new sendSms();

this.InitializeComponent();

if (!EventLog.SourceExists("Email2SMSSource"))

{

EventLog.CreateEventSource("Email2SMSSource", "Email2SMSLog");

}

this.EventLog1.Source = "Email2SMSSource";

this.EventLog1.Log = "Email2SMSLog";

this.Timer1.Elapsed += new ElapsedEventHandler(this.OnElapsedTime);

this.Timer1.Interval = 60 * Conversions.ToInteger(Conversions.ToString(1) + ConfigurationSettings.AppSettings["RecursiveOnce"]);

this.Timer1.AutoReset = true;

this.Timer1.Enabled = true;

}

protected void ConvertMail2SMS(int IterationCount)

{

if (IterationCount != 1)

{

string strLog = "Transaction Summary : \r\nProcess Initiated \r\n ";

POP3Client pop = new POP3Client();

pop.Host = ConfigurationSettings.AppSettings["POP3_Host"];

pop.Username = ConfigurationSettings.AppSettings["POP3_UserName"];

pop.Password = ConfigurationSettings.AppSettings["POP3_Password"];

try

{

pop.Connect();

strLog += "Login successfull \r\n ";

pop.Stat();

ReadyPOP3.Message[] messageArray = new ReadyPOP3.Message[pop.MessageCount + 1];

strLog += Conversions.ToString(pop.MessageCount) + " messages detected \r\n ";

int messageCount = pop.MessageCount;

for (int i = 1; i <= messageCount; i++)

{

strLog += "Screening Message " + Conversions.ToString(i) + " \r\n ";

string strEmailContents = pop.Retr(i);

messageArray[i] = new ReadyPOP3.Message(strEmailContents,false);

if (!String.IsNullOrEmpty(messageArray[i].SentTo) ||

!String.IsNullOrEmpty(messageArray[i].From))

{

string strFromName = this.GetFromName(messageArray[i].From.Trim());

strFromName = strFromName.Replace("\"", "");

strFromName = strFromName.Substring(0, 10); // Maximum length

strLog += "From Name " + strFromName + " \r\n ";

string strTrimmedRecipients = messageArray[i].SentTo.Trim().Replace(",", ";");

string[] strRecipients = strTrimmedRecipients.Split(new char[] { Convert.ToChar(";") });

foreach (string strRecipient in strRecipients)

{

string strFormattedRecipient = this.getMailFormat(strRecipient);

strLog += "To " + strFormattedRecipient + " \r\n";

string strMailDomain = ConfigurationSettings.AppSettings["MailDomain2Process"];

string strThisMailDomain = strFormattedRecipient.Split(new char[] { Convert.ToChar("@") })[1];

if (strThisMailDomain.Trim().ToUpper() == strMailDomain.ToUpper())

{

strLog += "To number contains " + ConfigurationSettings.AppSettings["MailDomain2Process"] + " \r\n ";

string strRecipientNumber = strFormattedRecipient.Split(new char[] { Convert.ToChar("@") })[0].Trim();

string strNumberLength = Conversions.ToString(Strings.Len(strRecipientNumber));

string strToNumber = strRecipientNumber;

strToNumber = strToNumber.ToString().Substring(0, 4);

strLog = (strLog + "Mobile length " + strNumberLength + " \r\n ") + "Prefix " + strToNumber + " \r\n ";

bool blnFailedToDiscoverPrefix = false;

try

{

this.Webservices4sendingSMS.Url = "http://www.freebiesms.co.uk/sendsms.asmx";

strLog += "Web Service triggered " + this.ParseXML(Conversions.ToInteger(strNumberLength), strToNumber, 2) + "/sendsms.asmx\r\n";

}

catch (Exception exPrefixDiscovery)

{

ProjectData.SetProjectError(exPrefixDiscovery);

blnFailedToDiscoverPrefix = true;

strLog += "No URL found for " + strRecipientNumber;

strLog += "(Length : " + strNumberLength + ")";

strLog += " Exception : " + exPrefixDiscovery.Message.ToString() + " \r\n";

ProjectData.ClearProjectError();

}

try

{

if (!blnFailedToDiscoverPrefix)

{

string strFromNumber = ConfigurationSettings.AppSettings["DefaultFromNumber"];

string strLocale = this.ParseXML(Conversions.ToInteger(strNumberLength), strToNumber, 1);

if (String.IsNullOrEmpty(strLocale))

{

throw new Exception(strToNumber + " is not a valid number format, or an unsupported destination");

}

this.Webservices4sendingSMS.SendSms(strFromName,

strFromNumber,

strRecipientNumber,

messageArray[i].Subject,

strLocale);

strLog += "From : " + messageArray[i].From;

strLog += " To : " + strRecipientNumber;

strLog += " Subject : " + messageArray[i].Subject;

strLog += " Locale : " + strLocale;

strLog += "Successfully sent message to " + strRecipientNumber + " \r\n ";

pop.Delete(i);

try

{

string strSMTPUserName = ConfigurationSettings.AppSettings["SMTP_UserName"];

string strToEmailAddress = this.GetMailAddress(messageArray[i].From.Trim());

this.SendMail(strSMTPUserName,

strToEmailAddress,

"Message sent",

"Successfully sent message to " + strRecipientNumber);

}

catch (Exception exFailedToEmailSender)

{

ProjectData.SetProjectError(exFailedToEmailSender);

strLog += "Error sending mail notification Exception : ";

strLog += exFailedToEmailSender.Message.ToString() + " \r\n";

ProjectData.ClearProjectError();

}

}

pop.Delete(i);

}

catch (Exception exErrorSendingMessage)

{

ProjectData.SetProjectError(exErrorSendingMessage);

strLog += " Error sending Message: ";

strLog += exErrorSendingMessage.Message.ToString() + " \r\n ";

string strSMTPUserName = ConfigurationSettings.AppSettings["SMTP_UserName"];

string strEmailRecipient = this.GetMailAddress(messageArray[i].From.Trim());

this.SendMail(strSMTPUserName,

strEmailRecipient,

"Message sending failed",

" Error sending Message- " + exErrorSendingMessage.Message.ToString());

ProjectData.ClearProjectError();

pop.Delete(i);

}

}

else

{

string strEMailDomain = ConfigurationSettings.AppSettings["MailDomain2Process"];

strLog += "To number doesn't contain " + strEMailDomain + " \r\n ";

pop.Delete(i);

}

}

}

else

{

// TO or FROM is empty.

strLog += " Invalid Email #" + i.ToString() + "\r\n";

pop.Delete(i);

}

}

}

catch(Exception exPopLogin)

{

strLog += "Login Failed. Please check the server name,username,password and Incoming port. \r\n";

strLog += exPopLogin.ToString();

}

pop.Quit();

pop.Disconnect();

this.EventLog1.WriteEntry(strLog + "Process completed");

}

}

[DebuggerNonUserCode]

protected override void Dispose(bool disposing)

{

try

{

if (((disposing && (this.components != null)) ? 1 : 0) != 0)

{

this.components.Dispose();

}

}

finally

{

base.Dispose(disposing);

}

}

public string GetFromName(string FromAddress)

{

if (FromAddress.Contains("<"))

{

return FromAddress.Substring(0, FromAddress.IndexOf("<"));

}

return FromAddress;

}

public string GetMailAddress(string FromAddress)

{

if (FromAddress.Contains("<"))

{

FromAddress = FromAddress.Replace(FromAddress.Substring(0, FromAddress.IndexOf("<")), "");

return FromAddress.Replace(">", "").Replace("<", "");

}

return FromAddress;

}

private string getMailFormat(string str)

{

if (str.IndexOf(">") > 0)

{

return Strings.Left(str.Split(new char[] { '<' })[1], str.Split(new char[] { '<' })[1].IndexOf(">"));

}

return str;

}

[DebuggerStepThrough]

private void InitializeComponent()

{

this.EventLog1 = new EventLog();

this.EventLog1.BeginInit();

this.ServiceName = "Mail2SMS";

this.EventLog1.EndInit();

}

[DebuggerNonUserCode, MTAThread]

public static void Main()

{

ServiceBase.Run(new ServiceBase[] { new Srvc_Mail2SMS() });

}

private void OnElapsedTime(object sender, ElapsedEventArgs e)

{

this.ConvertMail2SMS(2);

}

protected override void OnStart(string[] args)

{

}

protected override void OnStop()

{

this.Timer1.Enabled = false;

this.ConvertMail2SMS(2);

}

private string ParseXML(int len, string tono, int Typ)

{

XmlDocument node = new XmlDocument();

node.Load(ConfigurationSettings.AppSettings["SETTINGS_XML"]);

XmlNodeReader reader = new XmlNodeReader(node);

while (reader.Read())

{

switch (((int) reader.NodeType))

{

case 1:

if ((len == Conversions.ToInteger(reader.GetAttribute("MobileLength"))) & (Conversions.ToInteger(tono) == Conversions.ToInteger(reader.GetAttribute("Prefix"))))

{

this.Country = reader.GetAttribute("Locale");

this.website = reader.GetAttribute("Website");

}

break;

case 3:

Console.WriteLine(reader.Value);

break;

case 8:

Console.WriteLine("<!--" + reader.Value + "-->");

break;

case 15:

Console.WriteLine("</" + reader.Name + ">");

break;

case 0x11:

Console.WriteLine("<?" + reader.Name + " " + reader.Value + "?>");

break;

}

}

if (Typ == 1)

{

return this.Country;

}

return this.website;

}

public void SendMail(string strFrom, string strTo, string strSubject, string strMessage)

{

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

System.Net.Mail.MailMessage message2 = new System.Net.Mail.MailMessage(new MailAddress(strFrom.Trim()), new MailAddress(strTo));

message2.BodyEncoding = Encoding.UTF8;

message2.Subject = strSubject.Trim();

message2.Body = strMessage.Trim() + "\r\n";

message2.IsBodyHtml = true;

SmtpClient client = new SmtpClient(ConfigurationSettings.AppSettings["SMTP_Host"]);

client.Credentials = ((ICredentialsByHost)new NetworkCredential(ConfigurationSettings.AppSettings["SMTP_UserName"], ConfigurationSettings.AppSettings["SMTP_Password"]));

client.Port = (Conversions.ToInteger(ConfigurationSettings.AppSettings["SMTP_MailOutgoingPort"]));

client.Send(message2);

}

internal virtual EventLog EventLog1

{

[DebuggerNonUserCode]

get

{

return this._EventLog1;

}

[MethodImpl(MethodImplOptions.Synchronized), DebuggerNonUserCode]

set

{

this._EventLog1 = value;

}

}

}

}