如何将 UploadedFile 对象转换为 Swift_Mime_MimeEntity

How to convert UploadedFile object to Swift_Mime_MimeEntity

我有一个发送电子邮件的 Symfony 3.3 联系表。现在我正在尝试向表单添加附件。我在 sendEmail 函数中插入以下行:

        ->attach($data["attachment"])

...我收到以下错误:

Argument 1 passed to Swift_Mime_SimpleMessage::attach() must implement interface Swift_Mime_MimeEntity, instance of Symfony\Component\HttpFoundation\File\UploadedFile given

所以我的问题是:如何将我的 UploadedFile 对象转换成 SwiftMailer 会满意的对象?

====

编辑 #1:我尝试过但没有成功:

$fullFilePath = $data["attachment"]->getPath() . '/' . $data["attachment"]->getClientOriginalName();
$attachment = \Swift_Attachment::fromPath($fullFilePath);

附上那个 "attachment" 只是导致电子邮件没有被发送,尽管应用程序表现得好像它已经发送了表格。

====

编辑#2:进步!我现在能够得到一个有用的错误。此代码...

        $extension = $data["attachment"]->guessExtension();
    if($extension !== 'rtf'){
        die('Please give us an rtf file. TODO: Put a better message here!');
    }
    $newFilePath = '/tmp';
    $newFileName = 'temporary.rtf';
    $data["attachment"]->move($newFilePath, $newFileName);

...给我这样的错误:

Could not move the file "/tmp/phpnIqXDr" to "/tmp/temporary.rtf" ()

...这非常令人沮丧,因为我知道每个用户都可以写 /tmp

这是最终为我工作的代码:

private function sendEmail($data)
{
    $vgmsContactMail = self::contactMail;
    $mailer = $this->get('mailer');
    /* @var $uploadedFile UploadedFile */
    $uploadedFile = $data["attachment"];
    $extension = $uploadedFile->guessExtension();
    if(!in_array($extension, ['pdf','rtf']) ){
        die('Please upload a .pdf or .rtf file.');
    }
    $newFilePath = '/tmp';
    $newFileName = 'temporary' . rand(0,10000) . '.rtf';
    $uploadedFile->move($newFilePath, $newFileName);
    $attachment = \Swift_Attachment::fromPath('/tmp/' . $newFileName);
    $message = \Swift_Message::newInstance("VGMS Contact Form: ". $data["subject"])
        ->setFrom(array($vgmsContactMail => "Message by ".$data["name"]))
        ->setTo(array(
            $vgmsContactMail => $vgmsContactMail
        ))
        ->setBody($data["message"]."<br>ContactMail :".$data["email"])
        ->attach($attachment)
    ;
    return $mailer->send($message);
}

您不需要移动文件,Symfony\Component\HttpFoundation\File\UploadedFile class returns 路径并且有获取文件名和 mimetype 的方法。

这段代码对我有用:

$message->attach(
    \Swift_Attachment::fromPath($data["attachment"])
        ->setFilename(
            $data["attachment"]->getClientOriginalName()
        )
        ->setContentType(
            $data["attachment"]->getClientMimeType()
        )
);

归功于 toolpixx