How can PHP be used to extract and handle attachments from email bodies?
To extract and handle attachments from email bodies in PHP, you can use the PHP IMAP extension to connect to an email server, fetch the email containing attachments, and then use the MIME message parsing functions to extract and save the attachments to a specified directory.
// Connect to the IMAP server
$inbox = imap_open('{mail.example.com:993/imap/ssl}INBOX', 'username', 'password');
// Search for emails with attachments
$emails = imap_search($inbox, 'ALL');
// Loop through each email
foreach ($emails as $email_number) {
$structure = imap_fetchstructure($inbox, $email_number);
// Check if email has attachments
if (isset($structure->parts) && count($structure->parts)) {
foreach ($structure->parts as $part_number => $part) {
if ($part->ifdparameters) {
$filename = $part->dparameters[0]->value;
$attachment = imap_fetchbody($inbox, $email_number, $part_number + 1);
$decoded_attachment = base64_decode($attachment);
file_put_contents('attachments/' . $filename, $decoded_attachment);
}
}
}
}
// Close the connection
imap_close($inbox);