如何发送带附件的邮件

时间:2014-01-30 14:50:28

标签: php forms attachment

在网站上使用表格,我想先上传附件并将其发送到任意电子邮件地址。我曾尝试使用phpmailer,但我从未设法附加文件只是直接浏览它:

$mail->attachment("images/hello.jpg");

有谁知道如何解决这个问题,或PHPMailer的任何替代解决方案?

4 个答案:

答案 0 :(得分:1)

服务器处理上的这样的事情应该起作用:

if ($_FILES['file']['error'] <= 0 ){ // success, no error

    // read in the contents of temporary file
    $file_contents = file_get_contents( $_FILES['file']['tmp_name'] );

    // add the contents to phpmailer object, with original filename from upload
    $mail->addStringAttachment( $file_contents, $_FILES['file']['name'] );
}

这假设您的表单元素名为file,如:

<input type="file" name="file" />

答案 1 :(得分:0)

为此,您需要创建上传表单,有关详细信息,请参阅http://www.php.net/manual/en/features.file-upload.post-method.php。上传文件后,可以像在示例中一样将其附加到邮件中。然后,文件名将替换为保存上载的路径和文件名。

答案 2 :(得分:0)

http://www.finalwebsites.com/forums/topic/php-e-mail-attachment-script

尝试这个
<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }
}
?>

答案 3 :(得分:0)

您是否可能需要使用AddAttachment()而不是attachment()?

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

您可能还必须确保文件的路径与服务器上的脚本相关。

来自https://github.com/Synchro/PHPMailer