Thursday, June 4, 2009

How to send e-mail using C# with Attachment

Leave a Comment
When I am working in core asp mail sending is one of the biggest task.

For mail sending I have to check for third party on server. I have to according to third party avalibale on different server.

But, now say thanks to Microsoft who had made that task easy.

Sending a email using ASP.NET 2.0 and C# 2.0 is actually very simple.

First, you will need to import the System.Net.Mail namespace.

The System.Net.Mail namespace contains the SmtpClient and MailMessage Classes that we need in order to send the email.

You have to write this code to your page.

public static void Send(string SMTPServerName, string SMTPUserName, string SMTPPassWord, string MailFrom, string MailTo, string CC, string BCC, string Subject, string Body, bool BodyHTML, string Attachment)
{
MailMessage message = new MailMessage(MailFrom, MailTo, Subject, Body);

/******************************************/
//Adding multiple To Addresses
foreach (string sTo in MailTo.Split(",".ToCharArray()))
if (MailTo != sTo)
{
message.To.Add(sTo);
}

//Adding multiple CC Addresses
if (CC.Length > 0)
{
foreach (string sCC in CC.Split(",".ToCharArray()))
message.CC.Add(sCC);
}

//Adding multiple BCC Addresses
if (BCC.Length > 0)
{
foreach (string sBCC in BCC.Split(",".ToCharArray()))
message.Bcc.Add(sBCC);
}
//Adding multiple BCC Addresses
if (Attachment.Length > 0)
{
foreach (string sAttachment in Attachment.Split(",".ToCharArray()))
{
Attachment attachment = new Attachment(sAttachment);
message.Attachments.Add(attachment);
}
}
/******************************************/
SmtpClient emailClient = new SmtpClient(SMTPServerName);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(SMTPUserName, SMTPPassWord);
emailClient.UseDefaultCredentials = false;
emailClient.Credentials = SMTPUserInfo;
message.IsBodyHtml = BodyHTML;
emailClient.Send(message);
}

Or you can also download code from.
http://www.4shared.com/file/109821732/b8456382/SendMail.html

0 comments: