PHP的文件从表单上传到电子邮件 [英] Php file upload from form to email
本文介绍了PHP的文件从表单上传到电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图把一个文件作为联系表格的一部分上传,我希望上传的文件最终成为一封电子邮件的附件,然后我可以下载一次我收到的电子邮件。我已经得到了工作的形式,而不是作为一个附件来通过我的文件来通过这样的;
- == Multipart_Boundary_xc99bf5ef644b3e51650e68e4b9538cffx
Content-Type:application / pdf;
NAME = 360x260mm边缝口袋01 - 1UP B2.pdf
内容传输编码:的base64
JVBERi0xLjUNJeLjz9MNCjggMCBvYmoNPDwvTWV0YWRhdGEgOSAwIFIvT0NQcm9wZXJ0aWVzPDwv
RDw8L09OWzEwIDAgUl0vT3JkZXIgMTEgMCBSL1JCR3JvdXBzW10 + Pi9PQ0dzWzEwIDAgUl0 + Pi9Q
YWdlcyAyIDAgUi9UeXBlL0NhdGFsb2c + Pg1lbmRvYmoNOSAwIG9iag08PC9MZW5ndGggMTM0NTEv
U3VidHlwZS9YTUwvVHlwZS9NZXRhZGF0YT4 + c3RyZWFtDQo8P3hwYWNrZXQgYmVnaW49Iu + 7vyIg
aWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI / Pgo8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2Jl
Om5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIw
MTAvMDIvMTItMTc6MzI6
这是我的php;
$ b<?php
if(isset($ _ POST ['email'])){
$ email_to =matthew.p@cawthornes.co.uk;
$ email_subject =网站html表单提交;
函数已死($ error){
//错误代码
echo我们非常抱歉,但是发现了错误提交。
echo这些错误出现在下面。< br />< br />;
echo $ error。< br />< br />;
echo请回去修正这些错误。< br />< br />;
die();
//验证预期数据存在
if(!isset($ _ POST ['first_name'])||
!isset($ _ POST ['last_name '])||
!isset($ _ POST ['email'])||
!isset($ _ POST ['telephone'])||
!isset($ _ POST [服务'])||
!isset($ _ POST ['comments'])){
('我们很抱歉,但是您提交的表单看起来有问题。
}
$ first_name = $ _POST ['first_name']; //必需
$ last_name = $ _POST ['last_name']; //必需
$ email_from = $ _POST ['email']; //必需
$ telephone = $ _POST ['telephone']; //不需要
$ service = $ _POST ['service']; //不需要
$ comments = $ _POST ['comments']; //需要
/ * GET文件变量* /
$ tmpName = $ _FILES ['attachment'] ['tmp_name'];
$ fileType = $ _FILES ['attachment'] ['type'];
$ fileName = $ _FILES ['attachment'] ['name'];
$ error_message =;
$ email_exp ='/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2, 4} $ /';
if(!preg_match($ email_exp,$ email_from)){
$ error_message。='您输入的电子邮件地址似乎不是有效的。
}
$ string_exp =/ ^ [A-Za-z .'-] + $ /;
if(!preg_match($ string_exp,$ first_name)){
$ error_message。='您输入的名字看起来不是有效的。< br />';
if(!preg_match($ string_exp,$ last_name)){
$ error_message。='您输入的姓氏不是有效的。 ;
if(strlen($ comments)< 2){
$ error_message。='您输入的注释看起来不是有效的。
if(strlen($ error_message)> 0){
($ error_message);
}
$ email_message =下面的表格详细信息。\\\
\\\
;
$ b $函数clean_string($ string){
$ bad = array(content-type,bcc:,to:,cc:,href);
返回str_replace($ bad,,$ string);
$ b $ if(file($ tmpName)){
/ *读取文件('rb'=读取二进制文件)* /
$ file = fopen($ tmpName, 'RB');
$ data = fread($ file,filesize($ tmpName));
fclose($ file);
/ *一个边界字符串* /
$ randomVal = md5(time());
$ mimeBoundary === Multipart_Boundary_x {$ randomVal} x;
/ *文件附件标题* /
$标题。=\\\
MIME-Version:1.0 \\\
;
$ headers。=Content-Type:multipart / mixed; \\\
;
$ headers。=boundary = \{$ mimeBoundary} \;
/ *在消息上面的多部分边界* /
$ message =这是一个MIME格式的多部分消息。\\\ n。
- {$ mimeBoundary} \\\
。
Content-Type:text / plain; charset = \iso-8859-1 \\\\
。
Content-Transfer-Encoding:7bit \\\
。
$消息。 \\\
\\\
;
$ b $ * / *编码文件数据* /
$ data = chunk_split(base64_encode($ data));
$ b $ email_message。=名字:.clean_string($ first_name)。\\\
;
$ email_message。=姓氏:.clean_string($ last_name)。\\\
;
$ email_message。=Email:.clean_string($ email_from)。\\\
;
$ email_message。=电话:.clean_string($ telephone)。\\\
;
$ email_message。=服务:.clean_string($ service)。\\\
;
$ email_message。=评论:.clean_string($ comments)。\\\
;
/ *添加attchment-file到邮件* /
$ email_message。= - {$ mimeBoundary} \\\
。
Content-Type:{$ fileType}; \\\
。
name = \{$ fileName} \\\\
。
Content-Transfer-Encoding:base64 \\\ n。
$数据。 \\\
\\\
。
- {$ mimeBoundary} - \\\
;
//创建电子邮件标题
$ headers ='From:'。$ email_from。\r\\\
。
'回复:'。$ email_from。\r\\\
。
'X-Mailer:PHP /'。 phpversion();
@mail($ email_to,$ email_subject,$ email_message,$ headers);
函数IsInjected($ str)
{
$ injections = array('(\\\
+)',
'( \ r +)',
'(\ t +)',
'(%0A +)',
'(%0D +)',
'(%08 +) ',
'(%09 +)'
);
$ inject = join('|',$ injections);
$ inject =/ $ inject / i;
if(preg_match($ inject,$ str))
{
return true;
}
else
{
return false;
}
}
?>
<! - 成功的html - >
感谢您与我们联系。我们会尽快与您联系。
<?php
}
die();
?>
提前致谢。
方案为什么不使用 Swift Mailer
文档: Swift Mailer文档
下载: Swift-5.1.0
require_once'lib / swift_required.php';
//创建消息
$ message = Swift_Message :: newInstance()
//给消息一个主题
- > setSubject '您的主题')
//设置关联数组的$地址
- > setFrom(array('john@doe.com'=&'John Doe'))
//设置关联数组的地址
- > setTo(array(theceiver@domain.org','other@domain.org'=>'一个名字'))
//给它一个body
- > setBody('这里是消息本身')
//可选的另一个物体
- > addPart('< q>下面是消息本身< / q>','text / html')
//可选择添加任何附件
- > ;连接(Swift_Attachment :: fromPath( '我的-document.pdf'));
I am trying to get a file to upload as part of a contact form, i would like the uploaded file to end up as an attachement to an email that i can then download once i have received said email. I have got the form to work but instead of coming through as an attachment my file comes through like this;
--==Multipart_Boundary_xc99bf5ef644b3e51650e68e4b9538cffx
Content-Type: application/pdf;
name="360x260mm Side Seam Pocket 01 - 1up B2.pdf"
Content-Transfer-Encoding: base64
JVBERi0xLjUNJeLjz9MNCjggMCBvYmoNPDwvTWV0YWRhdGEgOSAwIFIvT0NQcm9wZXJ0aWVzPDwv
RDw8L09OWzEwIDAgUl0vT3JkZXIgMTEgMCBSL1JCR3JvdXBzW10+Pi9PQ0dzWzEwIDAgUl0+Pi9Q
YWdlcyAyIDAgUi9UeXBlL0NhdGFsb2c+Pg1lbmRvYmoNOSAwIG9iag08PC9MZW5ndGggMTM0NTEv
U3VidHlwZS9YTUwvVHlwZS9NZXRhZGF0YT4+c3RyZWFtDQo8P3hwYWNrZXQgYmVnaW49Iu+7vyIg
aWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/Pgo8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2Jl
Om5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIw
MTAvMDIvMTItMTc6MzI6
Here is my php;
<?php
if(isset($_POST['email'])) {
$email_to = "matthew.p@cawthornes.co.uk";
$email_subject = "website html form submissions";
function died($error) {
// error code
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['service']) ||
!isset($_POST['comments'])){
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$service = $_POST['service']; // not required
$comments = $_POST['comments']; // required
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Service: ".clean_string($service)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
/* Adding attchment-file to message*/
$email_message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<!-- success html -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
die();
?>
Thanks in advance.
解决方案
Why dont you use Swift Mailer
Docs : Swift Mailer Documentation
Downloads : Swift-5.1.0
require_once 'lib/swift_required.php';
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject('Your subject')
// Set the From address with an associative array
->setFrom(array('john@doe.com' => 'John Doe'))
// Set the To addresses with an associative array
->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
// Give it a body
->setBody('Here is the message itself')
// And optionally an alternative body
->addPart('<q>Here is the message itself</q>', 'text/html')
// Optionally add any attachments
->attach(Swift_Attachment::fromPath('my-document.pdf'));
这篇关于PHP的文件从表单上传到电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文