我正在尝试使用swftmailer - 从html网页上的表单上传文件(jpg,ppt,pdf,word等,最大上传例如:6MB), - 通过电子邮件发送表单内容附件通过swiftmailer。
我的表单已创建&我使用$ _POST来捕获thankyou.php页面中的字段值。电子邮件正在发送,但我无法附加文件!
上传/附加文件需要是一个选项,我发现一个在线资源,只有在上传文件时才发送信息,但情况并非总是如此,所以我转向swiftmailer看起来很棒,但是在文档/示例中,它还指定了上传附件的路径,我只是希望能够读入文件(不指定路径)并将其作为附件发送到给定的电子邮件地址以及其他表单字段,名称电子邮件,电话&消息。
非常感谢任何帮助。
我的HTML(contact.html)
<div id="form-main">
<div id="form-div">
<form class="form" method="post" action="thank-you.php" enctype="multipart/form-data">
<p class="name">
<input name="fieldFormName" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />
</p>
<p class="email">
<input name="fieldFormEmail" type="email" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />
</p>
<p class="phone">
<input name="fieldFormPhone" type="number" class="validate[required,custom[onlyLetter],length[0,20]] feedback-input" placeholder="Phone" id="phone" />
</p>
<p class="text">
<textarea name="fieldDescription" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>
</p>
<p class="upload">
<small>Send us a Drawing or file</small>
<input name="fieldAttachment" id="attachment" class="feedback-input" type="file">
</p>
<div class="submit">
<input type="submit" value="SEND" id="button-blue"/>
<div class="ease"></div>
</div>
</form>
</div>
</div>
我的PHP代码:
<?php
require_once 'lib/swift_required.php';
$fromEmail = $_POST['fieldFormEmail'];
$fromName = $_POST['fieldFormName'];
$fromPhone = $_POST['fieldFormPhone'];
$fromMessage = $_POST['fieldDescription'];
$fromAttachment = $_POST['fieldAttachment'];
// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
"sender@domain.com" => "Sender Name"
));
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody(
"From: " . $fromName . "\n" .
"Email: " . $fromEmail . "\n" .
"Phone: " . $fromPhone . "\n" .
"Message: " . $fromMessage . "\n"
);
$message->setFrom("$fromEmail", "$fromName");
// *** This is the part I am struggling to understand *** //
$message->attach(Swift_Attachment::newInstance('$fromAttachment'));
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
?>
提前谢谢
答案 0 :(得分:3)
替换您的代码
$message->attach(Swift_Attachment::newInstance('$fromAttachment'));
在此
$message->attach(
Swift_Attachment::fromPath($_FILES['fieldAttachment']['tmp_name'])->setFilename($_FILES['fieldAttachment']['name'])
);
答案 1 :(得分:2)
我已经使用了DarveL的代码,并添加了一个if语句来检查文件是否上传,因为如果用户没有附加文件,我仍然希望发送电子邮件。 下面的代码有效,所以现在我只需要添加一些文件类型/大小验证。
if(is_uploaded_file($_FILES['fieldAttachment']['tmp_name'])) {
$message->attach(
Swift_Attachment::fromPath($_FILES['fieldAttachment']
['tmp_name'])->setFilename($_FILES['fieldAttachment']['name'])
);
}
答案 2 :(得分:0)
检查表单上传。也许你有错误。
<form enctype="multipart/form-data" action="" method="POST">