Sunday, May 30, 2010

C# - Send email by using CDO

Ref:
http://support.microsoft.com/kb/310212


Example:
try
{
CDO.Message oMsg = new CDO.Message();
CDO.IConfiguration iConfg;

iConfg = oMsg.Configuration;

ADODB.Fields oFields;
oFields = iConfg.Fields;

// Set configuration.
ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];

//TODO: To send by using the smart host, uncomment the following lines:
//oField.Value = CDO.CdoSendUsing.cdoSendUsingPort;
//oField = oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"];
//oField.Value = "smarthost";

// TODO: To send by using local SMTP service.
//oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
//oField.Value = 1;

oFields.Update();

// Set common properties from message.

//TODO: To send text body, uncomment the following line:
//oMsg.TextBody = "Hello, how are you doing?";


//TODO: To send HTML body, uncomment the following lines:
//String sHtml;
//sHtml = "\n" +
// "\n" +
// "\n" +
// "\n" +
// "

\n" +
// "

Inline graphics

\n" +
// "\n" +
// "";
//oMsg.HTMLBody = sHtml;

//TOTO: To send WEb page in an e-mail, uncomment the following lines and make changes in TODO section.
//TODO: Replace with your preferred Web page
//oMsg.CreateMHTMLBody("http://www.microsoft.com",
// CDO.CdoMHTMLFlags.cdoSuppressNone,
// "", "");
oMsg.Subject = "Test SMTP";

//TODO: Change the To and From address to reflect your information.
oMsg.From = "someone@example.com";
oMsg.To = "someone@example.com";
//ADD attachment.
//TODO: Change the path to the file that you want to attach.
oMsg.AddAttachment("C:\\Hello.txt", "", "");
oMsg.AddAttachment("C:\\Test.doc", "", "");
oMsg.Send();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
return;
}