Home >Backend Development >PHP Tutorial >How to Attach Multiple Files to an Email Using PHP?

How to Attach Multiple Files to an Email Using PHP?

DDD
DDDOriginal
2024-11-02 16:20:29868browse

How to Attach Multiple Files to an Email Using PHP?

Attaching Multiple Files in Email via PHP

Problem:

The PHP code provided initially allows the attachment and sending of only a single file. However, the need arises to attach and send two files simultaneously, typically in different formats (e.g., RAR and PDF).

Solution:

To send multiple attachments in an email using PHP, modify the code as follows:

<br>$files = ['path/to/example.rar', 'path/to/example.pdf']; // Array of file paths</p>
<p>// ...</p>
<p>for($x=0;$x<count($files);$x  ){</p><pre class="brush:php;toolbar:false">$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";

}

Explanation:

  • The $files array contains the paths to the files that need to be attached.
  • The for loop iterates through the array, reads the file contents into the $data variable, and encodes it using base64.
  • The $message variable is appended with the appropriate headers for each file attachment, including the filename, content type, and base64-encoded data.
  • After all files are processed, the $message variable is ready to be sent as the email content.

The above is the detailed content of How to Attach Multiple Files to an Email Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn