Monday, June 16, 2008

Send an email with Attachment in C#.Net

Here is the method to send an attachment with mail.

using System.Web.Mail;

public string SendAttachmentEmail(string MailTo, string MailSubject, string MailBody, string AttachPDFPath, string MailFrom, string MailServer)
{
# region Email
try
{
try
{
MailMessage Message = new MailMessage();
Message.To = MailTo;
Message.From = MailFrom;
Message.Subject = MailSubject;
Message.Body = MailBody;
try
{
Message.Attachments.Add(new MailAttachment(AttachPDFPath));
}
catch (Exception ex)
{
return "Error while accessing attachemnt" + ex.ToString();
}
Message.BodyFormat = MailFormat.Html; //Specify mail format either text or html

try
{
SmtpMail.SmtpServer = MailServer; //Specify the exchange server name
SmtpMail.Send(Message);
return "true";
}
catch (System.Web.HttpException ehttp)
{
return ehttp.ToString();
}
}
catch (IndexOutOfRangeException ex)
{

return ex.ToString();
}
}
catch (System.Exception e)
{
return e.ToString();
}
# endregion
}

No comments: