0

I have a XML created and I want to send it as attachment to an email. How to do that using PHP? My code is not working

I have this

<?php
$mail_to = "";
$from_mail = "";
$from_name = "";
$reply_to = "";
$subject = "";
$message = "";

/* Attachment File */ // Attachment location

$file_name = "only1.php";
$path = "http://66.147.244.92/~homecre1/public_html/Test/only1.php;

// Read the file content

$file = $path.$file_name;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));

/* Set the email header */ // Generate a boundary

$boundary = md5(uniqid(time()));

// Email header

$header = "From: ".$from_name." \r\n";
$header .= "Reply-To: ".$reply_to."\r\n";
$header .= "MIME-Version: 1.0\r\n";

// Multipart wraps the Email Content and Attachment

$header .= "Content-Type: multipart/mixed;\r\n";
$header .= " boundary=\"".$boundary."\"";

$message .= "This is a multi-part message in MIME format.\r\n\r\n";
$message .= "--".$boundary."\r\n";

// Email content // Content-type can be text/plain or text/html

$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "$message_body\r\n";
$message .= "--".$boundary."\r\n";

// Attachment // Edit content type for different file extensions

$message .= "Content-Type: application/php;\r\n";
$message .= " name=\"".$file_name."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment;\r\n";
$message .= " filename=\"".$file_name."\"\r\n";
$message .= "\r\n".$content."\r\n";
$message .= "--".$boundary."--\r\n";

// Send email

if (mail($mail_to, $subject, $message, $header)) {
    echo "Sent";
} else {
    echo "Error";
}
?>
user4212650
  • 23
  • 1
  • 8
  • possible duplicate of [Send attachments with PHP Mail()?](http://stackoverflow.com/questions/12301358/send-attachments-with-php-mail) – Davide Pastore Nov 04 '14 at 10:04

1 Answers1

0

If you are using PhpMailer library then use the following function to add the file.

$mail->AddAttachment("filename");

PHPMailer library Link : https://github.com/PHPMailer/PHPMailer

Vijay
  • 278
  • 5
  • 19
  • is there any option without PHPMailer? – user4212650 Nov 04 '14 at 10:13
  • Please go through the mailer function it explains to how to send it. http://php.net/manual/en/function.mail.php you to write your own function for it. One guy has written genric funciton with name public static function prepareAttachment($path) { – Vijay Nov 04 '14 at 11:12