首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >有时不包括PHPmailer附件

有时不包括PHPmailer附件
EN

Stack Overflow用户
提问于 2018-06-21 15:11:34
回答 1查看 144关注 0票数 0

我使用PHPmailer发送邮件。

代码语言:javascript
复制
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From      = 'some address';
$mail->FromName  = 'some name';
$mail->Subject   = 'some subject';
$mail->Body      = $bodytext;
$mail->IsHTML(true); 
$mail->AddAddress('some email');

// FILES
for($i = 0; $i < $length; $i++) 
{
    $filedata['name'] = $_FILES['userfile']['name'][$i];

    $path = "somepath";     
    move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $path);
    {    
        $stmt = $pdo->prepare("INSERT...");
        $stmt->execute($filedata);

        $mail->AddAttachment( $path, $filedata['name']);
    }
}

$mail->Send();

问题是,有时(不总是)的附件不包括在电子邮件中,但总是上传到服务器和添加到数据库。

有什么问题吗?也许,在addAttachment的时刻move_uploaded_file还没有完成上传?

EN

回答 1

Stack Overflow用户

发布于 2018-06-21 18:25:56

您需要检查文件是否正确上载,文件是否为空,以及PHPMailer是否可以加载它。

转述the PHPMailer example

代码语言:javascript
复制
try {
    for ($i = 0; $i < $length; $i++) {
        if ((int)$_FILES['userfile']['size'][$i] === 0) {
            throw new RuntimeException('Zero length file; may exceed allowed size.');
        }
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$i]));
        $filename = $_FILES['userfile']['name'][$i];
        if (!move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile)) {
            throw new RuntimeException("Failed to move file $filename to $uploadfile");
        }
        if (!$mail->addAttachment($uploadfile, $filename)) {
            throw new RuntimeException("Failed to attach file $filename");
        }
        //Everything is ok, so do whatever else you need to do, like store the record in the DB
    }
} catch (RuntimeException $e) {
    echo 'File upload failed:', htmlspecialchars($e->getMessage());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50962478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档