Friday, February 29, 2008

How To Send a Simple E-mail in Asp.net

How to Send a Simple E-Mail In Asp.net

This is the Code for sending an e-mail with attachment and without attachments (Asp.net & C#.net)


In Desing Page take a text boxes controls for from,to,Bcc,Subject,messages

and a fileupload control for Attachment and one button control to send the mail

In button control writethe following code:

Using.System.IO;

Using .System.web.mail;

protected void btnSubmit_Click(object sender, EventArgs e)
{

MailMessage mail = new MailMessage();
mail.From = txtFrom.Text;
mail.To = txtTo.Text;
mail.Bcc = txtbcc.Text;

mail.Subject = txtSubject.Text;
mail.Body = txtMsg.Text;
mail.BodyFormat = MailFormat.Html;
//string s;

if (txtFile.Value == “”)
{
try
{
SmtpMail.Send(mail);
}
catch (Exception ex)
{
Response.Write(”Exception Occured: ” + ex);
}
finally
{
Response.Write(”Your E-mail has been sent sucessfully”);
}

}
else
{

string strdir = “D:\\temp\\”;

string strfilename = Path.GetFileName(txtFile.PostedFile.FileName);

txtFile.PostedFile.SaveAs(strdir + strfilename);

mail.Attachments.Add(new MailAttachment(strdir + strfilename));

try
{
SmtpMail.Send(mail);
}
catch (Exception ex)
{
Response.Write(”Exception Occured: ” + ex);
}
finally
{
Response.Write(”Your E-mail has been sent sucessfully”);
}

// Uploaded file deleted after sending e-mail

File.Delete(strdir + strfilename);
}

}

We can send the mail with attachment are with out attachment

Give the feed back ….

No comments :

Post a Comment