Friday, April 25, 2008

Send Email with attachment (using System.Web.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (btn_Send) and Lable control
and Required Validator for txtFrom , txtSubject and Fileupload control


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
using System.IO;


public partial class SendEmail : System.Web.UI.Page
{
string strPath;

protected void Page_Load(object sender, EventArgs e)
{

}

private bool SendMail()
{
try
{

/* Create a new blank MailMessage */
MailMessage mailMessage = new MailMessage();

mailMessage.From = txtTo.Text;

mailMessage.To = "y.ahmed@ewebbers.com";

mailMessage.Subject = txtSubject.Text ;

msgMail.Body = txtMessage.Text ;

/* We use the following variables to keep track of
attachments and after we can delete them */

string attach1 = null;

/*strFileName has a attachment file name for attachment process. */

string strFileName = null;

if (FileUpload1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = FileUpload1.PostedFile;

/* Get size of the file */
int attachFileLength = attFile.ContentLength;

/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
/* Get the file name */
strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

/* Save the file on the server */
FileUpload1.PostedFile.SaveAs(Server.MapPath(strFileName));

/* Create the email attachment with the uploaded file */
MailAttachment attach = new MailAttachment(Server.MapPath(strFileName));

/* Attach the newly created email attachment */
mailMessage.Attachments.Add(attach);

/* Store the attach filename so we can delete it later */
attach1 = strFileName;
}

/* Set the SMTP server and send the email with attachment */
SmtpMail.SmtpServer = ("SMTP.ewebbers.com");

SmtpMail.Send(mailMessage);

/* Delete the attachements if any */
if (attach1 != null)
{
File.Delete(Server.MapPath(attach1));
}
}

return true;
}
catch (Exception ex)
{
return false;
}
}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool TrueOrFalse = SendMail();

if ((TrueOrFalse == true))
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}
}
}

No comments: