PHPmail with attachment doesn't reach Gmail + formatting errors

I use phpmail script to send attachments from site to e-mail. The script itself works. I noticed that e.g. in the case of Gmail messages are coming but without attachments. Instead, in addition to the content, there is a very long message containing only the hash string.

In addition, not all mailboxes display content correctly. In some cases, the content also adds, for ex.:

–PHP-alt-41babb7e7ab4c64e3af6ea533924bebdContent-Type: text/plain; charset=“UTF-8” Content-Transfer-Encoding: 7bit

and the html coding in plain text.

Can it be standardized so as not to display unnecessary information?

Here’s my code:

<?php
$to = $_POST['email'];
$subject = 'Attachment from site domain.com';
$subject = sprintf("=?utf-8?B?%s?=", base64_encode($subject));
$random_hash = md5(uniqid(time()));

$headers = "From: MySite <[email protected]>\r\nReply-To: [email protected]";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

$filename = $_POST['file_id'] . ".pdf";
$path = "/home/ftp/wp-content/uploads";
$file = $path . "/" . $filename;

// read file into $data var
$f = fopen($file, "rb");
$data = fread($f,  filesize( $file ) );
fclose($f);

$attachment = chunk_split(base64_encode($data));

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="UTF-8"
Content-Transfer-Encoding: 7bit

Hello,
Here the mail text.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: 8bit

<h2>Hello,</h2>
<p>Here's the mail text</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Transfer-Encoding: base64
Content-Type: application/pdf; name="<?php echo $filename; ?>"
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
$message = ob_get_clean();
if (@mail($to, $subject, $message, $headers )) {
    echo "<p><b>File send!</b></p> Check your e-mail.";
} else {
    echo "<p><b>Error!</b></p> File not send.";
}
?>

What can I change to make delivery with an attachment work for all mailboxes?

Ever thought to use PHPMailer or SwiftMailer ?

Yes, but I use it in Wordpress. I made small modifications and the attachment is already being sent. The problem is only that the attachment in the incoming email is corrupted. It cannot be opened.

Sponsor our Newsletter | Privacy Policy | Terms of Service