Thursday, April 2, 2009

sending email with attachment using Attachment Class

For sending email with attachment we usally upload file on server and after sending the email delete it from sever. but .net 2.0 interdues new class Attachment which provide us a eazy way with IO.Stream and filename. this class has a constructor that allows you to pass an IO.Stream and a file name. Conveniently, the FileUpload control has a FileContent property that returns the uploaded file as an IO.Stream. All that's left to do is to

get the file name from the uploaded file using Path.GetFileName and you're good to go.


private void functionSendMailWithAttachment(FileUpload FileUpload1)
{

if (FileUpload1.HasFile)
{
string toAddress = "reciver@gmail.com";
string fromAddress = "admin@helpondesk.com";
string mailServer = "smtp.server.com";

MailMessage myMailMessage = new MailMessage();

myMailMessage.To.Add(toAddress);
myMailMessage.From = new MailAddress(fromAddress);
myMailMessage.Subject = "Never :) ";


string fileName = FileUpload1.PostedFile.FileName;
Attachment myAttachment = new Attachment(FileUpload1.FileContent, fileName);
myMailMessage.Attachments.Add(myAttachment);

SmtpClient mySmtpClient = new SmtpClient(mailServer);
//if you want to send mail from local host.
/// SmtpClient smtpClientho = new SmtpClient("localhost");


mySmtpClient.Send(myMailMessage);
}


}

Add fileupload control on aspx page.

[asp:FileUpload ID="FileUpload1" runat="server" /]

namespace
using System.Net.Mail;

Thanks
Helpondesk Team

No comments: