Thursday, April 9, 2009

How to Send Email in ASP.net with Attachment



Requirements for use this Code
1.Visual studio
2.IIS

Try this code

In Asp.net, we have a default object called MailMessage, we can use this object to create,sendmails,delete attachments etc...

Create Object

Mailmessage MM=new Mailmessage();

if(Radiobutton.selectedItem.Text="Text")
{
MM.BodyFormat = MailFormat.Text;

}
else
{
MM.BodyFormat = MailFormat.Html;

}
MM.From = txtSender.Text;
MM.To = txtReceiver.Text;
MM.Subject = txtSubject.Text;
MM.Body = txtBody.Text

if(attachemnt.Postedfile!=null)
{
HttpPostedFile File= attachemnt.PostedFile;
if( File.ContentLength > 0 )
{
strFileName = Path.GetFileName(attachemnt.PostedFile.FileName);
strFileName = "attachments/" + strFileName;
attachemnt.PostedFile.SaveAs(Server.MapPath(strFileName));
MailAttachment Att= new MailAttachment(Server.MapPath(strFileName));
MM.Attachments.Add(Att);
Att= strFileName;
}

}


SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (MM);

No comments: