I’m using PHPMailer 6.8.1 and I don’t want to upload the file (which can be an image, pdf, or a docx) to the server before sending it by email. This call doesn’t work:
$mail->addAttachment($_FILES['document']['tmp_name'], $_FILES['document']['name']);
I get an error thay says "Could not access file".
But if I upload the file with move_uploaded_file()
and then give the full path of the uploaded file to the addAttachment()
function, then it works like a charm and I receive the mail with the file.
Is it possible to send the file without saving it on the server?
2
Answers
If you have a value in the POSTed
$_FILES
, you at that point have already Uploaded the file (at least) in a temp folder on the server.. so at that point you can move it.. attach it and it works… as expected.The only way to email a file which is not attached, in any way, is to link it (from a public endpoint), not "attach it"
Regular PHP file uploads (i.e. anything involving
$_FILES
) will always arrive at your script as files on disk. There’s not really any way around that specific mechanism.You can however handle uploads in an entirely different way, using Javascript to do the upload as a kind of stream, and this will arrive in your script as a property of
$_REQUEST
. This is limited by memory size of course.In PHPMailer you can attach a string from memory as an attachment using
addStringAttachment()
, which would work like this:MIME type and encoding are set automatically.