Auto attach file in php mail

I want to send a PDF file to php mail. I know the name and location of the file (invoice printed in cup-pdf) and would like to send this automatically to php when I click the button on my website. How can this be done? Thanks

+3
source share
2 answers

You must use one of the classes built for this, for example PEAR Mail . For a more detailed explanation, assuming that we are using only plain UTF8 text with a PDF file.

  • uniqboundary should be replaced with some unique string
  • $fileType is the MIME type of your file.

Here is the code:

$headers = 'MIME-Version: 1.0'."\r\n"
    .'Content-Type: multipart/related; boundary="--uniqboundary"'."\r\n";

$body = '--uniqboundary."\r\n".
    .'Content-Type: text/plain; charset=utf-8'."\r\n"
    .'Content-Transfer-Encoding: 8bit'."\r\n\r\n"
    .$text
    .'--uniqboundary'."\r\n"
    .'Content-Type: '.$fileType.'; name="'.basename($filename).'"'."\r\n"
    .'Content-Transfer-Encoding: base64'."\r\n"
    .'Content-Disposition: attachment; filename="'.basename($filename).'"'."\r\n\r\n";

$lineSize = filesize($filename) + 1;
$f = fopen($filename, 'r');
$chunks[] = chunk_split(base64_encode(fread($f, $lineSize)));
fclose($f);

$body .= implode("\r\n", $chunks)
    .'--uniqboundary--'."\r\n";

mail($to, $subject, $body, $headers);

It should work.

+2
source

phpmailer - , smtp.

0

Source: https://habr.com/ru/post/1748019/


All Articles