Monday, August 3, 2009

Outlook Mailing

Create an Util Class as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Net.Mime;
using log4net.Repository;
using log4net;
using System.Reflection;
using log4net.Appender;

namespace PWCSecurities.Utils
{
public class OutlookEmailHelper
{
#region Logging

private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

#endregion

private Outlook._Application outlookApp;
private Outlook.NameSpace outlookNameSpace;
private Outlook.MAPIFolder maipFolder;
private Outlook._MailItem mailItem;



public delegate void MessageSentHandler(object sender, MessageSentEventArgs e);
public event MessageSentHandler MessageSent;

public string MailSubject = "SecurityTool Error Report";

//static SmtpClient smtpClient = new SmtpClient("mailhost.lehman.com");

public Outlook._MailItem MessageItem
{
get
{
return mailItem;
}
set
{
mailItem = value;
}

}

public OutlookEmailHelper()
{
try
{
outlookApp = new Outlook.Application();
outlookNameSpace = outlookApp.GetNamespace("MAPI");
outlookNameSpace.Logon(null, null, true, true);

// Gets defaultfolder for my Outlook Outbox
maipFolder = outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);

//create a a new mailitem object
mailItem = (Outlook.MailItem)outlookApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

}
catch (Exception)
{
}

}

///
///
///

///
/// Outlook Mail Recipient Type : To = 1 and Cc = 2
///
public string Resolve(string[] names, object type)
{
Outlook.OlMailRecipientType recType;
if ((string)type == "1")
{
recType = Microsoft.Office.Interop.Outlook.OlMailRecipientType.olTo;
}
else
{
recType = Microsoft.Office.Interop.Outlook.OlMailRecipientType.olCC;
}
return Resolve(names, mailItem, recType);
}

///
///
///

///
///
///
///
public string Resolve(string[] names, Outlook._MailItem mailItem, Outlook.OlMailRecipientType type)
{
string resolvedNames = string.Empty;
Outlook.Recipients or = mailItem.Recipients;
//Add recipients
foreach (string strName in names)
{
try
{
if (string.IsNullOrEmpty(strName))
continue;
Outlook.Recipient rec = or.Add(strName);
// if cannot be resolved remove from the recipients collection
rec.Resolve();

if (!rec.Resolved)
{
rec.Delete();
}
else
{
//type = cc
rec.Type = (int)type;
resolvedNames += rec.Name + ";";

}
}
catch (System.Exception)
{
}
}
return resolvedNames;
}

void outlookApp_ItemSend(object Item, ref bool Cancel)
{
try
{
// outlookApp.ItemSend -= new Microsoft.Office.Interop.Outlook.ApplicationEvents_10_ItemSendEventHandler(m_olApp_ItemSend);

Outlook._MailItem oMailItem = Item as Outlook._MailItem;

string toIds = string.Empty;
string ccIds = string.Empty;
foreach (Outlook.Recipient rec in oMailItem.Recipients)
{
if (rec.Type == 1)
toIds += rec.Name + ";";
else if (rec.Type == 2)
ccIds += rec.Name + ";";
}

if (MessageSent != null)
this.MessageSent(oMailItem, new MessageSentEventArgs(oMailItem.Subject, toIds, ccIds));
}
finally
{
outlookNameSpace.Logoff();
outlookNameSpace = null;
outlookApp = null;
}
}


public void SendMail(string toAddress, string body)
{
SendMail(toAddress, "SecurityTool Support", body);
}

public void SendMail(string toAddress, string subject, string body)
{
SendMail(toAddress, "", subject, body, null);
}

public void SendMail(string toAddress, string ccAdress, string subject, string body)
{
SendMail(toAddress, ccAdress, subject, body, null);
}

public void SendMail(string toAddress, string ccAdress, string subject, string body, IList attachments)
{
SendMail(toAddress, ccAdress, subject, body, attachments, null);
}

public void SendMail(string toAddress, string ccAdress, string subject, string body, IList attachments, IList attachmentsDisplayNames)
{
try
{
Logger.Debug("Create the mail item...");
// Creates a new MailItem object
mailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

//resolve the address to make sure we don't have any junk values.
toAddress = Resolve(toAddress.Split(';'), mailItem, Outlook.OlMailRecipientType.olTo);

if(toAddress == string.Empty)
throw new MailException("Unable to resolve the name");
// mailItem.To = toAddress;
//resolve the address to make sure we don't have any junk values.
ccAdress = Resolve(ccAdress.Split(';'), mailItem, Outlook.OlMailRecipientType.olCC);
//oMailItem.Recipients.Remove(2);

// mailItem.CC = ccAdress;
mailItem.Subject = subject;
mailItem.Body = body;
mailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
mailItem.SaveSentMessageFolder = maipFolder;

if (attachments != null && attachments.Count > 0)
{
for (int i = 0, iPosition = mailItem.Body.Length + 1; i < attachments.Count; i++, iPosition++)
{
string fileName = attachments[i];

int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
mailItem.Attachments.Add(attachments[i], iAttachType, iPosition, attachmentsDisplayNames[i]);
Logger.Debug("Adding the attachment " + fileName);
}
}
Logger.Debug("Sending the mail item");
// adds it to the outbox
mailItem.Send();
Logger.Debug("EMail sent successfully to " + toAddress);
}
catch (Exception e)
{
throw new MailException(e.Message, e);
}
finally
{

//Logger.Debug("Disposing outlook objects...");
//oMailItem = null;
//m_olSentFolder = null;
//m_olNameSpace.Logoff();
//m_olNameSpace = null;
//m_olApp = null;
}
}

//public static void SendMail(string body)
//{
// try
// {
// MailMessage msg = new MailMessage("prashkum@lehman.com", "prashkum@lehman.com", "SecurityTool Error Report", body);

// //Environment.GetEnvironmentVariable("Temp")+"\\SecurityPricing.log";
// string logFile = "C:\\Edit Sets to Group Error.txt";//GetCurrentLogFileName();

// // Create the file attachment for this e-mail message.
// Attachment attData = new Attachment(logFile, MediaTypeNames.Application.Octet);
// // Add time stamp information for the file.
// ContentDisposition disposition = attData.ContentDisposition;
// disposition.CreationDate = System.IO.File.GetCreationTime(logFile);
// disposition.ModificationDate = System.IO.File.GetLastWriteTime(logFile);
// disposition.ReadDate= System.IO.File.GetLastAccessTime(logFile);

// msg.Attachments.Add(attData);

// smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
// smtpClient.Send(msg);
// }
// catch (Exception ex)
// {

// }
//}


}

///
/// Exception wrapper for any exceptions thrown from IMailHandler
///

public class MailException : System.Exception
{
public MailException()
{
}

public MailException(string message)
: base(message)
{
}

public MailException(string message, Exception innerException)
: base(message, innerException)
{
}
}

public class MessageSentEventArgs : EventArgs
{
private string m_subject;
private string m_to;
private string m_cc;

public MessageSentEventArgs(string subject, string to, string cc)
{
this.m_subject = subject;
this.m_to = to;
this.m_cc = cc;
}

public string Subject
{
get
{
return m_subject;
}
set
{
m_subject = value;
}
}

public string To
{
get
{
return m_to;
}
set
{
m_to = value;
}
}

public string CC
{
get
{
return m_cc;
}
set
{
m_cc = value;
}
}
}
}



Use the send method from the above class to send mails from the outlook

No comments: