寻找帮助我的人。
我的网站上有一个邮件脚本用于发送电子邮件,发送邮件工作正常,但我希望能够发送带附件的电子邮件,我遇到了问题。
这是表单的php
<?php
// Set email variables
$email_to = 'youremail@address.com';
$email_subject = 'Form submission';
// Set required fields
$required_fields = array('fullname','email','comment');
// set error messages
$error_messages = array(
'fullname' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field]))array_push $validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content- Type:", "bcc:","to:","cc:"), '', $field));
}
?>
答案 0 :(得分:0)
检查此答案:Send attachments with PHP Mail()?
我建议使用Swift mailer。使用它我取得了很大的成功。它不仅有助于附件,还允许您发送HTML电子邮件,而不会将邮件程序发送到垃圾邮件。
以下是PHP中普通邮件功能的一些代码:找到here在带附件的发送邮件下。
<?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";
?>
答案 1 :(得分:0)
假设您的表单具有此输入字段
<label for="Attachment">Attachment:</label>
<input type="file" name="attach1" id="attach1" />
以下功能将完成发送附件的工作,它需要参数$ recipientEmail,$ senderEmail,$ subject,$ message,只要您在表单提交上有上述输入字段,附件就会被$ _FILE处理
public function sendEmailWithAttachments($recipientEmail,$senderEmail, $subject,$message){
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","JPG","png","PNG","rtf","txt","xml");
$files = array();
foreach($_FILES as $name=>$file) {
//die("file size: ".$file['size']);
if($file['size']>=5242880)//5mb
{
$fileSize=$file['size'];
return false;
}
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
return false;
//die("File $file_name has the extensions $ext which is not allowed");
}
//move the file to the server, cannot be skipped
$server_file="/tmp/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
array_push($files,$server_file);
//array_push($files,$temp_name);
}
// email fields
$headers = "From: $senderEmail";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
return @mail($recipientEmail, $subject, $message, $headers);
}