尝试使用 html 表单中的 mail() 自动发送内联和/或附件,但不断获取二进制字符串
Posted
技术标签:
【中文标题】尝试使用 html 表单中的 mail() 自动发送内联和/或附件,但不断获取二进制字符串【英文标题】:Trying to automatically send an inline and/or attachment with mail() from a html form, but keep getting binary string 【发布时间】:2012-04-11 10:48:31 【问题描述】:我正在尝试为我正在设计的俱乐部制作电子邮件表单,我希望它检查我是否在 html 电子邮件中包含附件或内联图像。到目前为止一切正常,除了当我尝试包含附件时,它会在 90 秒时超时,并且它会发送一些电子邮件,并且开头充满了“---- Content-Type: application/pdf; name= "BrainMonkey-ooPic-RS.pdf" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="test-RS.pdf" 然后是代表文件的二进制字符串,最后是 html 电子邮件当然少发附件了,代码如下:
<?php
//------------------------ Check if Subject is filled out ------------------------------>
if (isset($_POST['subject']))
//-------------- Upload File from User Computer for attachment ------------------------->
$target_path = "attachments/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_path))
$file_location = $target_path;
$fileatt = $file_location;
$fileattname =basename($file_location);
// read file into $data var
$file = fopen($fileatt, "rb");
$data = fread($file, filesize( $fileatt ) );
fclose($file);
// split the file into chunks for attaching
$content = chunk_split(base64_encode($data));
$isattached = "yes";
echo "Attachment attached ".$fileattname." uploaded and is good!";
else
$isattached = "no";
echo "No Attachment sent ".$fileattname;
//------------ Upload File from User Computer for inline image ------------------------>
$target_path2 = "attachments/";
$target_path2 = $target_path2 . basename( $_FILES['file2']['name']);
if(move_uploaded_file($_FILES["file2"]["tmp_name"], $target_path2))
$file_location2 = $target_path2;
$fileatt2 = $file_location2;
$fileattname2 =basename($file_location2);
$inline = '<tr><td><center><img src="http://www.mywebsite.com/JWEC/JWECMail/'. $target_path2 .'"></center><br></td></tr>';
echo "Inline Attached ".$inline;
else
$inline = ' ';
echo "<br>No Inline Attached ".$inline."<br>";
//------------------- Set up From, Replyto, and $message ------------------------------>
$name = "ME";
$from = "myemail@mywebsite.com";
$replyto= $from;
$message = $_REQUEST['message'];
//------------------------ Setup Header -------------------------------------------->
// handles mime type for better receiving
if ($isattached == "yes")
$ext = strrchr( $fileatt , '.');
echo $ext;
$ftype = "";
if ($ext == ".doc") $ftype = "application/msword";
if ($ext == ".jpg") $ftype = "image/jpeg";
if ($ext == ".gif") $ftype = "image/gif";
if ($ext == ".png") $ftype = "image/png";
if ($ext == ".zip") $ftype = "application/zip";
if ($ext == ".pdf") $ftype = "application/pdf";
if ($ftype=="") $ftype = "application/octet-stream";
//$uid = md5(uniqid(time()));
//---------------------------- Connect to DB ------------------------------------------>
$con = mysql_connect("mywebsitemysql.com","username","password");
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("database");
//----------------------- Select First Names and Emails --------------------------->
$result = mysql_query("SELECT fname, email FROM table");
if(mysql_num_rows($result) <= 0)
echo "<div class=\"box red\"><center>Email Submissions Failed, No members to send to.</center></div>";
else
$count = 0;
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC))
//---------------------- Set To & Subject -------------------------------------------->
$to = $row['email'];
$subjectf = $_POST["subject"];
$subject = "Here is a " . $subjectf . " for you ";
$person = $row['fname'];
$footer = "<br><br> Best Regards,<br> My Website Club br><br> If you feel we have sent this email to you in error, or if you <br> would like to be removed from future JW Elite Club emails, you may unsubscribe here:<br> http://www.mywebsite.com/JWEC/unsubscribe.php?email=".$to."<br>";
//------------------------- Message --------------------------------------------------->
$messagehtml = "
<html>
<head></head>
<body>
<table border='0' cellpadding='0' cellspacing='0' align='center' width='550'>
<tr><td><img src='http://www.mywebsite.com/JWEC/JWECMail/include/header.jpg' width='550' alt='My Website Club'><br><br></td></tr>
<tr><td>Dear " . $person . ",<br><br></td></tr>
<tr><td>" . $message . "<br><br></td></tr>
".$inline."
<tr><td>" . $footer . "<br></td></tr>
<tr><td><img src='http://www.mywebsite.com/JWEC/JWECMail/include/footer.jpg' width='550' alt='My Company and My Website - Keep Walking'><br><br></td></tr>
</table>
</body>
</html>
";
//------------------ Set Headers ------------------------------------------------->
// build the headers for attachment and html
"--$mime_boundary--\n";
$h = "From: $name<$from>" . "\r\n";
$h .= "Reply-To: $from"."\r\n";
$h .= "Return-Path: $from" . "\n";
$h .= "Date: ".date("r")."\n";
$h .= "MIME-Version: 1.0\n";
$h .= "Content-type:text/html; charset=iso-8859-1 \n";
$h .= "--$mime_boundary--";
if ($isattached == "yes")
$h .= "Content-Type: ".$ftype."; name=\"".basename($fileatt)."\"\r\n";
$h .= "Content-Transfer-Encoding: base64\r\n";
$h .= "Content-Disposition: attachment; filename=\"".basename($fileatt)."\"\r\n\r\n";
$h .= $content."\r\n";
$h .= "--$mime_boundary--";
// send mail
if (mail($to, $subject, $messagehtml, $h))
$count++;
echo "Fileattname = ".$fileattname." | Inline = ".$inline."<br><br>";
echo "<div class=\"box green\"><center>$count Emails Sent.</center></div>";
else ?>
<form name='Sendhtml' action='' method='post' enctype='multipart/form-data'><br />
Subject: <input id='subject' name='subject' /><br/><br/>
Message: <br /><br /><textarea name="message" cols="40" rows="15"></textarea><br /><br />
Include Image?<br /><br/><input type='file' name='file2' id='file2' /><br/><br/>
Include Attachment?<br /><br /><input type='file' name='file' id='file' /><br/><br/>
<input type='submit' name='submit' value='Submit' /> <input type='reset' value='Reset' />
</form>
<?php ?>
我很确定问题出在标题 ($h) 上,但我不确定是什么问题。请帮忙。
提前谢谢你,
罗伯特
【问题讨论】:
也许你应该考虑使用 PHPMailer 或 SwiftMail。你会避免头疼的(我也会这样做,为你提供这个答案,对不起!) 我知道这会更容易,但我宁愿自己做,这样我就能确切地知道发生了什么。感谢您的建议,尽管我会调查它。 【参考方案1】:我会坚持我的旧建议使用... PHPMailer
网址:http://code.google.com/a/apache-extras.org/p/phpmailer/
下载链接:http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/detail?name=PHPMailer_5.2.1.zip&can=2&q=
示例代码
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->AddAddress('whoto@otherdomain.com', 'John Doe');
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
catch (phpmailerException $e)
echo $e->errorMessage(); //Pretty error messages from PHPMailer
catch (Exception $e)
echo $e->getMessage(); //Boring error messages from anything else!
测试了这段代码 20 次,它工作得非常好......
谢谢 :)
=============== 丢弃旧消息 ============
你有一些关键标题丢失的例子:
$h.= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
您的某些标题格式也不正确,我建议您使用 PHPMailer,如果您想要一个简单的发送邮件功能,您可以在下面使用这个...(不包括验证)
【讨论】:
没有用,只有一个主题的黑色电子邮件,或者当我尝试使用附件时附件已损坏。 @RonertH .. 请使用更新后的代码 .. 效果很好.. 试了 20 次【参考方案2】:好吧,我得到了它,当然标题完全错误,谢谢大家的帮助。万一有人需要,这里是新的 header 和 mail() 部分!
//Setup Headers
if ($isattached == "yes")
$ext = strrchr( $fileatt , '.');
$ftype = "";
if ($ext == ".doc") $ftype = "application/msword";
if ($ext == ".jpg") $ftype = "image/jpeg";
if ($ext == ".gif") $ftype = "image/gif";
if ($ext == ".png") $ftype = "image/png";
if ($ext == ".zip") $ftype = "application/zip";
if ($ext == ".pdf") $ftype = "application/pdf";
if ($ftype=="") $ftype = "application/octet-stream";
// read file into $data var
$file = fopen($fileatt, "rb");
$data = fread($file, filesize( $fileatt ) );
fclose($file);
// split the file into chunks for attaching
$content = chunk_split(base64_encode($data));
$rand = md5( time() );
$mime_boundary = '==Multipart_Boundary_' . $rand;
$h = "From: $name<$from>" . "\n";
$h .="Reply-To: $from"."\n";
$h .= "Return-Path: $from" . "\n"
."MIME-Version: 1.0\n" .
"Content-Type: multipart/mixed; boundary=\"" . $mime_boundary . "\""
."\n\n";
$message = "This is a multi-part message in MIME format.\n\n" .
"--" . $mime_boundary . "\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$body . "\n\n";
if ($content)
$message .= "--" . $mime_boundary . "\n" .
"Content-Type: \"" . $ftype . "\";\n" .
" name=\"" . basename($fileatt) . "\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"" . basename($fileatt) . "\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$content . "\n\n" .
"--" . $mime_boundary . "--\n";
// send mail
$sent = mail($to, $subject, $message, $h);
$count++;
if ($sent)
echo "<div class=\"box green\"><center>$count Emails Sent.</center></div>";
else
echo "<div class=\"box red\"><center>$count Emails Sent.</center></div>";
再次感谢您的帮助!
罗伯特
【讨论】:
以上是关于尝试使用 html 表单中的 mail() 自动发送内联和/或附件,但不断获取二进制字符串的主要内容,如果未能解决你的问题,请参考以下文章
通过电子邮件发送带有 PHP 和 HTML 错误消息“Cannot POST mail.php”的表单
使用 mail() PHP 脚本的 jQuery AJAX 表单发送电子邮件,但来自 HTML 表单的 POST 数据未定义