使用 SwiftMailer 的 PHP 附件

Posted

技术标签:

【中文标题】使用 SwiftMailer 的 PHP 附件【英文标题】:PHP attachment using SwiftMailer 【发布时间】:2012-01-28 16:20:22 【问题描述】:

我正在学习使用 SwiftMailer,但无法从 输入类型。我不应该只需要:

<input name="attachment" id="attachment" type="file">

然后

$message = Swift_Message::newInstance()
->attach(new Swift_Message_Attachment(new Swift_File($file), $filename,));

这是我的完整代码

<?php
if (!empty($_POST)) 

$success = $error = false;

$post = new stdClass;

$file = $_FILES["attachment"]["tmp_name"]; //"attachment" is the name of your input field, "tmp_name" gets the temporary path to the uploaded file.

$filename = $_FILES["attachment"]["name"]; //"name" gets the filename of the uploaded file.         

foreach ($_POST as $key => $val)
    $post->$key = trim(strip_tags($_POST[$key]));

    if (empty($post->name) OR empty($post->email))
    $error = true;

else 

    $dir = dirname(__FILE__);

    ob_start();
    require_once($dir.'/pdf.php');
    $pdf_html = ob_get_contents();
    ob_end_clean();

    require_once($dir.'/dompdf/dompdf_config.inc.php');

    $dompdf = new DOMPDF();
    $dompdf->load_html($pdf_html);
    $dompdf->render();
    $pdf_content = $dompdf->output();

    ob_start();
    require_once($dir.'/html.php');
    $html_message = ob_get_contents();
    ob_end_clean();

    require_once($dir.'/swift/swift_required.php');

    $mailer = new Swift_Mailer(new Swift_MailTransport());

    $message = Swift_Message::newInstance()
                   ->setSubject('Order Entry') // Message subject
                   ->setTo(array('ehilse@paifashion.com' => 'Eric Hilse')) // Array of people to send to
                   ->setFrom(array('no-reply@paifashion.com' => 'PAi Order Entry'))
                   ->setBody($html_message, 'text/html') // Attach that HTML message from earlier
                   ->attach(Swift_Attachment::newInstance($pdf_content, 'design.pdf', 'application/pdf')); // Attach the generated PDF from earlier
                   ->attach(new Swift_Message_Attachment(new Swift_File($file), $filename));
    // Send the email, and show user message
    if ($mailer->send($message))
        $success = true;
    else
        $error = true;




?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>PAi Cap &amp; Tee Art Pack Order Form</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>

<body>

<div id="container">
            <div id="logo">
                <img src="images/pailogo.png" id="logo" />
            </div>
        <h1><abbr title="Paramount Apparel International">PAi</abbr> Cap &amp; Tee Art Pack Order Form</h1>

        <?php if ($success)  ?>
            <div class="message success">
                <h4>Congratulations! It worked! Your order has been sent.</h4>
            </div>
        <?php  elseif ($error)  ?>
            <div class="message error">
                <h4>Sorry, an error occurred. Try again!</h4>
            </div>
        <?php  ?>

        <form method="post" action="" enctype="multipart/form-data">
            <fieldset>
                <legend>Please fill in the following form:</legend>
                    <label for="name">Your Name:<span class="required">*</span></label>
                    <input type="text" name="name" id="name" class="input" />

                    <label for="email">Your Email:<span class="required">*</span></label>
                    <input type="text" name="email" id="email" class="input" />     

        <br />

                    <label for="artpacknumber">Art Pack Number:<span class="required">*</span></label>
                    <input type="text" name="artpacknumber" id="artpacknumber" class="input" />         

                    <label for="language">New Or Revise?<span class="required">*</span></label>
                    <select name="language" id="language">
                        <option value="NEW">New</option>
                        <option value="REVISE">Revise</option>
                    </select>

        <br />  

                    <label for="duedate">Due Date:<span class="required">*</span></label>
                    <input type="text" name="duedate" id="duedate" class="input" />

                    <label for="dateentered">Date Entered:<span class="required">*</span></label>
                    <input type="text" name="dateentered" id="dateentered" class="input" />

        <br />

                    <label for="designname">Design Name:<span class="required">*</span></label>
                    <input type="text" name="designname" id="designname" class="input" />

        <br />

                    <label for="customer">Customer:<span class="required">*</span></label>
                    <input type="text" name="customer" id="customer" class="input" />

                    <label for="account">Account:<span class="required">*</span></label>
                    <input type="text" name="account" id="account" class="input" />

        <br />

                    <label for="salesrep">Sales Rep:<span class="required">*</span></label>
                    <input type="text" name="salesrep" id="salesrep" class="input" />

                    <label for="extension">Extension:<span class="required">*</span></label>
                    <input type="text" name="extension" id="extension" class="input" />

        <br />

                    <label class="commentslabel" for="comments">Comments:<span class="required">*</span></label>
                    <textarea name="comments" id="comments" rows="4" cols="40"></textarea>

        <br />

                    <label for="attachment">File Upload<br />.</label>
                    <input name="attachment" id="attachment" type="file">

        <br />          

                    <input type="submit" class="submit" id="submit" value="Submit" />

        </fieldset>

    </form>

</div>

这是我的新错误 [27-Dec-2011 14:51:58] PHP 已弃用:函数 set_magic_quotes_runtime() 在第 4332 行的 /Applications/MAMP/htdocs/paipdf2/dompdf/lib/class.pdf.php 中已弃用

[27-Dec-2011 14:51:58] PHP 已弃用:函数 set_magic_quotes_runtime() 在 /Applications/MAMP/htdocs/paipdf2/dompdf/lib/class.pdf.php 第 4348 行已弃用

[27-Dec-2011 14:51:58] PHP 警告:require_once(/Applications/MAMP/htdocs/paipdf2/dompdf/include/swift_message_attachment.cls.php) [function.require-once]:无法打开流:第 194 行的 /Applications/MAMP/htdocs/paipdf2/dompdf/dompdf_config.inc.php 中没有这样的文件或目录

[2011 年 12 月 27 日 14:51:58] PHP 致命错误:require_once() [function.require]:无法打开所需的 '/Applications/MAMP/htdocs/paipdf2/dompdf/include/swift_message_attachment.cls.php ' (include_path='.:/Applications/MAMP/bin/php/php5.3.6/lib/php') 在 /Applications/MAMP/htdocs/paipdf2/dompdf/dompdf_config.inc.php 第 194 行

【问题讨论】:

Swift Mailer attachments 的可能重复项 - 要了解上传文件的位置,请参阅:php.net/manual/en/features.file-upload.php 【参考方案1】:

好吧,在包含 Swiftmailer 之前包含 DOMpdf 时会出现问题。

我还没有找到错误的原因,但我确实有解决方案。

在 'dompdf_config.inc.php' 中更改代码的和平:

function DOMPDF_autoload($class) 
  $filename = mb_strtolower($class) . ".cls.php";
  require_once(DOMPDF_INC_DIR . "/$filename");

到这里:

function DOMPDF_autoload($class) 
  $filename = mb_strtolower($class) . ".cls.php";
  if (file_exists(DOMPDF_INC_DIR . "/$filename")) 
    require_once(DOMPDF_INC_DIR . "/$filename");
  

更改后它可以工作,您可以使用 swiftmailer 邮寄您的 pdf。

额外信息。我如何启动 DomPDF:

require_once("lib/dompdf/dompdf_config.inc.php");
spl_autoload_register('DOMPDF_autoload'); 
$dompdf = new DOMPDF();
$dompdf->load_html($pdfhtml);
$dompdf->set_paper('a4', 'portrait');
$dompdf->render();
$dompdf->stream("invoice", array('Attachment'=>0));

【讨论】:

【参考方案2】:

我猜$file$filename 没有携带文件路径和名称的实际值。

假设表单发布正确,要访问上传文件的路径,您必须使用$_FILES 超全局数组,如下所示:

$file = $_FILES["attachment"]["tmp_name"]; //"attachment" is the name of your input field, "tmp_name" gets the temporary path to the uploaded file.
$filename = $_FILES["attachment"]["name"]; //"name" gets the filename of the uploaded file.
$message = Swift_Message::newInstance()
->attach(new Swift_Message_Attachment(new Swift_File($file), $filename));

文档:http://www.php.net/manual/en/reserved.variables.files.php

【讨论】:

我用你所说的添加了我的完整代码,但由于某种原因它完全破坏了它。你能说出我做错了什么吗? 你确定你的代码被第二个if 语句移动过去了吗?此外,如果显示任何错误或警告,也请分享。 这是我收到的唯一错误 PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /Applications/MAMP/htdocs/paipdf2/form.php on line 49 您在第 49 行多了一个不应该出现的分号。删除它,看看会发生什么。 好吧,我把它拿出来了,现在它给了我 2 个新错误 PHP 注意:未定义的变量:第 77 行的 /Applications/MAMP/htdocs/paipdf2/form.php 中的成功和未定义的变量:错误/Applications/MAMP/htdocs/paipdf2/form.php 第 81 行

以上是关于使用 SwiftMailer 的 PHP 附件的主要内容,如果未能解决你的问题,请参考以下文章

使用 SwiftMailer 为 text/html 和 text/plain 使用附件

php发邮件:swiftmailer, php邮件库——swiftmailer

PHP - 使用 STARTTLS 和自签名证书的 Swiftmailer

如何在 Symfony2 中使用 Swiftmailer 将 PDF 附加到电子邮件

使用 Swiftmailer 的 PHP 驱动的 HTML 联系表单有多安全?

使用 php、gmail 和 swiftmailer 发送电子邮件会导致与 SSL 相关的错误