我需要随邮件发送一份pdf,可以吗?
$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: xxx <xxx>' . "\r\n";
mail($to,$subject,$message,$headers);
我错过了什么?
我同意评论中的@MihaiIorga -使用PHPMailer脚本。听起来你拒绝是因为你想要更简单的选择。相信我,比起自己使用PHP内置的mail()函数,PHPMailer是一个更简单的选择。PHP的mail()函数真的不是很好。
使用PHPMailer:
下载PHPMailer脚本:http://github.com/PHPMailer/PHPMailer
提取归档文件并将脚本文件夹复制到项目中方便的位置。
包括主脚本文件——require_once('path/to/file/class.phpmailer.php');
现在,发送带有附件的电子邮件从异常困难变得异常简单:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );
$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );
return $email->Send();
只有一行$email-> addatattachment ();——再简单不过了。
如果使用PHP的mail()函数,则需要编写大量代码,并且可能会遇到许多很难找到的错误。
ContactRequestSubmittedName:'.$name.'
Email:'.$email.'
Subject:'.$subject.'
Message:
'.$message.'
';$headers="From:$fromName"."";if(!empty($uploadedFile)&&file_exists($uploadedFile)){$semi_rand=md5(time());$mime_boundary="==Multipart_Boundary_x{$semi_rand}x";$headers.="\nMIME-Version:1.0\n"."Content-Type:multipart/mixed;\n"."boundary=\"{$mime_boundary}\"";$message="--{$mime_boundary}\n"."Content-Type:text/html;charset=\"UTF-8\"\n"."Content-Transfer-Encoding:7bit\n\n".$htmlContent."\n\n";if(is_file($uploadedFile)){$message.="--{$mime_boundary}\n";$fp=@fopen($uploadedFile,"rb");$data=@fread($fp,filesize($uploadedFile));@fclose($fp);$data=chunk_split(base64_encode($data));$message.="Content-Type:application/octet-stream;name=\"".basename($uploadedFile)."\"\n"."Content-Description:".basename($uploadedFile)."\n"."Content-Disposition:attachment;\n"."filename=\"".basename($uploadedFile)."\";size=".filesize($uploadedFile).";\n"."Content-Transfer-Encoding:base64\n\n".$data."\n\n";}$message.="--{$mime_boundary}--";$returnpath="-f".$email;$mail=mail($toEmail,$emailSubject,$message,$headers,$returnpath);@unlink($uploadedFile);}else{$headers.="\r\n"."MIME-Version:1.0";$headers.="\r\n"."Content-type:text/html;charset=UTF-8";$mail=mail($toEmail,$emailSubject,$htmlContent,$headers);}if($mail){$statusMsg='Yourcontactrequesthasbeensubmittedsuccessfully!';$msgClass='succdiv';$postData='';}else{$statusMsg='Yourcontactrequestsubmissionfailed,pleasetryagain.';}}}}else{$statusMsg='Pleasefillallthefields.';}}?>">"placeholder="Name"required="">"placeholder="Emailaddress"required="">"placeholder="Subject"required="">[Source][1]
https://www.findinall.com/blog/how-to-test-mail-and-send-attachment-in-mail/
这对我很有用。它还附加了多个附件。很容易
<?php
if ($_POST && isset($_FILES['file'])) {
$recipient_email = "recipient@yourmail.com"; //recepient
$from_email = "info@your_domain.com"; //from email using site domain.
$subject = "Attachment email from your website!"; //email subject line
$sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
$sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
$sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['file'];
//php validation
if (strlen($sender_name) < 4) {
die('Name is too short or empty');
}
if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
die('Invalid email');
}
if (strlen($sender_message) < 4) {
die('Too short message! Please enter something');
}
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("specialToken$4332"); // boundary token to be used
if ($file_count > 0) { //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:" . $from_email . "\r\n";
$headers .= "Reply-To: " . $sender_email . "" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($sender_message));
//attachments
for ($x = 0; $x < $file_count; $x++) {
if (!empty($attachments['name'][$x])) {
if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
$mymsg = array(
1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3 => "The uploaded file was only partially uploaded",
4 => "No file was uploaded",
6 => "Missing a temporary folder");
die($mymsg[$attachments['error'][$x]]);
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= "--$boundary\r\n";
$body .= "Content-Type: $file_type; name=" . $file_name . "\r\n";
$body .= "Content-Disposition: attachment; filename=" . $file_name . "\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
$body .= $encoded_content;
}
}
} else { //send plain email otherwise
$headers = "From:" . $from_email . "\r\n" .
"Reply-To: " . $sender_email . "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $sender_message;
}
$sentMail = @mail($recipient_email, $subject, $body, $headers);
if ($sentMail) { //output success or failure messages
die('Thank you for your email');
} else {
die('Could not send mail! Please check your PHP mail configuration.');
}
}
?>
要发送带有附件的电子邮件,我们需要使用multipart/mixed MIME类型,该类型指定混合类型将包含在电子邮件中。此外,我们希望使用多部分/替代MIME类型来发送纯文本和HTML版本的电子邮件。看一下这个例子:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
正如你所看到的,发送带有附件的电子邮件很容易完成。在前面的例子中,我们有多部分/混合MIME类型,在里面我们有多部分/替代MIME类型,指定两个版本的电子邮件。为了将附件包含到消息中,我们将指定文件中的数据读入一个字符串,使用base64对其进行编码,将其分割为更小的块,以确保它与MIME规范匹配,然后将其作为附件包含。
从这里拍的。