Tuesday, April 29, 2008

ASP.NET, Sending mail with attachment

Unlike PHP, sending mail out with ASP.NET is always troublesome especially if you are sending it from a shared hosting company and you don't have much access towards it except using FTP. I was having a major headache while trying to send email out from client's hosting site while it has been working properly on my development server. The problem started when i'm trying to send the email with the attachment. I cant get proper permission for the folder to upload the attachment thus giving me trouble to upload the file and attach it. I found several solutions which at the end only one of them that helps. This is one of the solution which i found STUPID:

"
Dim msg As New Net.Mail.MailMessage(txtFrom.Text,txtTo.Text,txtSubject.Text,txtMessage.Text)

If fileUpload.PostedFile.FileName = "" Then
Else
msg.Attachments.Add( New System.Net.Mail.Attachment(fileUpload.PostedFile.FileName))
End If"


taken from this stupid site He didn't even bother to use fileUpload.HasFile to check if the control has any file attached to it but use .Filename ="" instead. Either lazy or stupid programmer.

At the end I managed to find a solution which I think it's the best for my situation which I can't upload the file to a folder those, by using stream I can attach the file without even executing any IO to the disk. Superb!!

 if (attachFile.PostedFile != null && 
attachFile.PostedFile.ContentLength > 0)
{
// attachFile.PostedFile.FileName contains
// the full path of the file. We only want the file
// so we delimit it by forward slashes into an array

string[] tempFileName =
attachFile.PostedFile.FileName.Split('\\');

// attachFile.PostedFile exposes a System.IO.Stream
// property named InputStream

Attachment emailAttach = new Attachment(
attachFile.PostedFile.InputStream,
tempFileName[tempFileName.Length - 1]);

email.Attachments.Add(emailAttach);
}
attachFile is a FileUpload control and email is a MailMessage class. :) You can read the whole solution here

Cheers,
Hatim

4 comments:

nagakeciks said...

nice....

post a banyok lagik tips...senang aku buat rujukan nanti...

Radius said...

hahahhahhahahha maleh sket ndak taip la brader... busy smacam... nantilah kalo aku ada masa... aku akan taip

Name Company said...

same lahh hahaha tu r nnt bila nk guna blk bru kelam kabot google balik kan hhheehe

Anonymous said...

hi, found your blog through realm of skicekagan. m just starting to study ASP so this post is really helpful.

thanks for sharing the codes! ^_^