How to email attachment from PHP?

2020-08-03 09:21发布

问题:

I am trying to email a text file as an attachment from a PHP script using the code from here: http://webcheatsheet.com/php/send_email_text_html_attachment.php#attachment

<?
$subject = 'Requested File';
$random_hash = md5(date('r', time()));
$headers = "From: email@email.com\r\nReply-To: email@email.com";
$headers .= "\r\nContent-Type: myltipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents('path/test.txt')));

ob_start();
?>

--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="test.txt"  
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"; 
?>

I'm not a PHP developer and have very limited experience using it, I am not getting any errors when this script is executed but I am also not receiving the email...any ideas why? Or what I should be looking at specifically?

Thank you for any tips!

EDIT: As per the comments, I tried using SwiftMailer but I cannot get it to work using this code: $message = Swift_Message::newInstance();

// Give the message a subject
$message->setSubject('Your subject');

// Set the From address with an associative array
$message->setFrom(array('email@email.com' => 'From Name'));

// Set the To addresses with an associative array
$message->setTo(array('email@email.com', 'email@email.com' => 'Name'));

// Give it a body
$message->setBody('Here is the message itself');

// And optionally an alternative body
$message->addPart('<q>Here is the message itself</q>', 'text/html');

// Optionally add any attachments
$message->attach(Swift_Attachment::fromPath('path/test.csv'));

Again, this code executes without any errors but no email is sent...what am I missing?

回答1:

That tutorial has errors for its file attachment, I remember it now and I never could modify it to work. (In the past)

Here is a working copy from my own library that you're welcome to use.

Just change all instances of test.txt to the file you wish to attach.

<html>
<head>
<title>Send file attachments using PHP</title>
</head>
<body>
<?php
  $to = "email@example.com";
  $subject = "This is the subject";
  $message = "This is the test message.";
  # Open a file
  $file = fopen( "test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));

  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:email@example.com\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>