phpMailer sending attachment name, not attachment

2019-07-16 13:38发布

Hi I have a file upload field with name="file1" and code in a phpmailer script:

if (isset($_FILES['file1']))
{
$file1_path = $_FILES['file1']['tmp_name'];
$file1_name = $_FILES['file1']['name'];
$file1_type = $_FILES['file1']['type'];
$file1_error = $_FILES['file1']['error'];
$mail->AddAttachment($file1_path);
}

And for some reason, it attached like php45we34 (each time diff, seems that its the temp name path, not the actual file)

Any help?

3条回答
我只想做你的唯一
2楼-- · 2019-07-16 14:05

Strip spaces from your filename!

Blue hills.jpg should be Blue_hills.jpg

do

$fileName = str_replace(' ', '_', $fileName);

查看更多
Melony?
3楼-- · 2019-07-16 14:07

I suggest you to use function move_uploaded_file before adding attachment.

This is sample code that will move file from temporary location somewhere at your server

$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}

After that AddAttachment should work fine.

$mail->AddAttachment(basename($target_path . $_FILES['uploadedfile']['name']));
查看更多
够拽才男人
4楼-- · 2019-07-16 14:08

What you see is what should happen. You do not specify the attachment name, so phpMailer uses the name of the temporary file it's attaching.

If you want the file to have a different name, you have to specify it. The accepted answer works because it goes the other way round -- it changes the file name so that the file has the desired name.

The usual way to proceed would be to issue

$mail->AddAttachment($file1_path, $_FILES['file1']['name']);

to override the attachment name.

查看更多
登录 后发表回答