Avatar of robnhood00
 asked on

upload file using ajax and send as email attachment without saving to server

I'm trying to upload a file using ajax to a vb.net handler and then sending that file as an email attachment without saving the file to the server.  I've tried several examples that I've found online, however, I'm not getting anywhere.
AJAX.NET Programming

Avatar of undefined
Last Comment

8/22/2022 - Mon

I was able to get this to work using the code below, however, it saves the file to the server first.  Does anyone know how to code it without saving it?
Dim fileName As String = HttpContext.Current.Request.QueryString("FileName").ToString
        Dim fs As FileStream = File.Create((context.Server.MapPath("~/" + fileName)))
        Dim buffer() As Byte = New Byte(((32 * 1024)) - 1) {}
        Dim read As Integer = context.Request.GetBufferlessInputStream.Read(Buffer, 0, Buffer.Length)
        While (read > 0)
            fs.Write(Buffer, 0, read)
            read = context.Request.GetBufferlessInputStream.Read(Buffer, 0, Buffer.Length)
        End While

        'Mail File
        Dim myMail As New System.Net.Mail.MailMessage("web@domain.com", "test@domain.com", "test", "Attachement test")
        Dim mail As New System.Net.Mail.SmtpClient()
        myMail.Attachments.Add(item:=New Attachment(HttpContext.Current.Server.MapPath("~/" & filename)))
        myMail.IsBodyHtml = True
        myMail = Nothing
        fs = Nothing

Open in new window

Robert Schutt

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

I tried the example above with the results below:
The First Solution
Sometimes it sent and sometimes it did not.  When it does send what appears to be a partial version of the file.  I attached a 30kb file and what was sent was a 3kb file.  

The Second Solution
Worked fine consistently.  Thanks!
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy