Jump to content

PHP attached images wont display in the emails


mark107

Recommended Posts

Hi all,

I need some help with my code as I've a trouble with sending the emails with images attachments. I'm using Pear Mail library to send the emails so when I send the emails with attachments to gmail, I am unable to see the attached images in my gmail inbox as there is no images show on the bottom of the subject unless when I open on my email so I can see the images attachments. And I am unable to see the images on yahoo when i sent the emails, so I sent a test email on my webmail with the images as attachments and I can see the images on gmail and yahoo with no problem. I think there is a problem with my PHP script that need to be resolve. 

Here is where I am getting the problem with:
       

//attachments
        if (is_array($email_attachments)) {
            foreach ($email_attachments as $attachments) {
                $filename = str_replace('uploads/', '', $attachments);
                $attachment = '';
                $file_path = '';
                $type = '';

                if (strpos($filename, '.png') !== false) {
                    $type .= 'image/png';
                }
    
                // ADD attachment(s)
                $attachment1 .= "--$boundary1\r\n";
                $attachment1 .= "Content-Type: $type; name=\"$filename\"\r\n";
                $attachment1 .= "Content-Transfer-Encoding: base64\r\n";
                $attachment1 .= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
                $attachment1 .= "\r\n\r\n";
                $attachment1 .= $attachment;
                $attachment1 .= "\r\n\r\n";

                $body .= $attachment1;
                $mime->addAttachment($file_path, $type);
            }
        }

 

 

Here is the full code:

<?php

require_once('Mail.php');
require_once('Mail/mime.php');
require_once('Mail/IMAPv2.php');

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

//Connect to the database
include('config.php');

// Connect to the server:
$username = 'myusername';
$password = 'mypassword';
$smtp_hostname = "smtp.mydomain.com";
$port = "587";
$attached_files = array();
$inline_images = array();
global $inline_images;

if (isset($_POST['send_to']))
{
    $from = "Mark <name@mydomain.com>";
    $to_email = $_POST['send_to'];
    $subject = $_POST['email_subject'];
    $message ='<div dir="ltr">' . $_POST['email_body'] . '</div>';
    $email_attachments = $_POST['email_attachment'];
    $total_emails = count($to_email);
    $email_number = $_POST['email_number'];
    $sent_message = $message;
    $attachment1 = '';
    $inline_id = 0.1;
    $success = '';
    $base64 = [];
    $src = [];

    //Check if the images is base64
    if (strpos($message, 'data:image/') !== false)
    {
        // read all image tags into an array
        preg_match_all('/<img.*?src="data:image\/.*;.*,(.*)".*?>/i', $message, $match, PREG_PATTERN_ORDER);
        $base64 = array_pop($match);

        if (is_array($src)) 
        {
            foreach($base64 as $images)
            {
                $type = end(explode('/', (explode(';', $images))[0]));
                $filename = md5(time().uniqid()). '.' . $type;
                $base64_string = str_replace('data:image/png;base64,', '', $images);
                $base64_string = str_replace(' ', '+', $base64_string);
                $decoded = base64_decode($base64_string);
                $fp = fopen("uploads/". $filename, "w+");
                fwrite($fp, $decoded);
                fclose($fp);
            }
        }
    }

    //check if the inline images is in the array
    if (strpos($message, '<img src=') !== false)
    {
        // read all image tags into an array
        preg_match_all('@src="([^"]+)"@' , $message, $match);
        $src = array_pop($match);

        if (is_array($src)) 
        {
            foreach ($src as $key => $value)
            {
                $parsed = parse_url($src[$key]);
                $filename = basename($parsed['path']);
                $content = file_get_contents($src[$key]);

                if (!file_exists($filename))
                {
                    $fp = fopen("uploads/". $filename, "w+");
                    fwrite($fp, $content);
                    fclose($fp);
                }
            }
        }
    }
    $boundary1 = '###'.md5(microtime()).'###';
    $boundary2 = '###'.md5(microtime().rand(99,999)).'###';


    foreach ($to_email as $to)
    {
        $name = '';
        $email = '';


        if (strpos($to, ' <') !== false) {
            $name_str = explode(' <', $to);
            $email_str = explode(' <', $to);
            $name = $name_str[0];
            $email = str_replace('>', '', $email_str);
            $email = $email[1];
        }
        $messageID = sprintf("<%s.%s@%s>",
            base_convert(microtime(), 10, 36),
            base_convert(bin2hex(openssl_random_pseudo_bytes(8)), 16, 36),
            'mydomain.com');
        $message_id = getMessageid(isset($message_id));
        $now = new DateTime();
        $email_id = $now->getTimestamp();
        $sent_date = date('Y-m-d H:i:s');
        $sent_mailbox1 = $link->prepare("SELECT * FROM sent WHERE message_id = ?");
        $sent_mailbox1->execute([$message_id]);
        $emailID = '';
        
        if (!$name == '' && !$email == '') {
            if ($name == $email) {
                $to = $email;
            }
        }


        if ($sent_mailbox1->rowCount() == 0)
        {
            $sent_mailbox1 = $link->prepare("INSERT INTO sent (from_email, to_email, message_id) VALUES (?,?,?)");
    
            if ($sent_mailbox1->execute([$from, $to, $message_id]))
            {
                $emailID = $link->lastInsertId();
            }
        }


        //check if the images is base64
        if (is_array($base64)) 
        {
            $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view';
            $inline_id += 0.1;
        }
        else if (!$base64 == '') {
            $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view';
            $inline_id += 0.1;
        }


        //check if the inline images is in the array
        if (is_array($src)) 
        {
            $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view';
            $inline_id += 0.1; 
        }
        else if (!$src == '') {
            $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view';
            $inline_id += 0.1;
        }
        $message .= '<img src="http://mydomain.com/track/Images/signature.gif?id='.$emailID.'&etc='.time(). '" ' . 'style="width:0;max-height:0;overflow:hidden" alt="">';


        $headers = array ('From' => $from, 
            'To' => $to, 
            'Subject' => $subject,
            'Reply-To' => $from,
            //'Content-Type'  => 'Content-Type: text/plain; charset="UTF-8"',
            'Content-Type'  => 'Content-Type: multipart/mixed; boundary="=_d909e7abc497193ad3b6636530382391"',
            'MIME-Version' => '1.0',
            'Received' => 'from mail.mydomain.com',
            'Date'  => date("r"),
            'Message-ID' => '<'.sha1(microtime(true)).'@mydomain.com>');


        $crlf = "\r\n";
        $mime = new Mail_mime(array('eol' => $crlf));
        //$mime = new Mail_mime("\r\n");
        $html = $message;
        $text = strip_tags($html);
        $body = $html;

        $mime->setTXTBody($text);
        $mime->setHTMLBody($html);

        //check if the img tags have url called display=view
        if (strpos($message, 'display=view') !== false) {
            $pattern = '@src="([^"]+)"@';
            $message = preg_replace_callback($pattern,"setImageLinks", $message);
    
            foreach ($inline_images as $inline_image) {
                $file_path =  $inline_image;
                $typeInt = imagetype($file_path);
    
                //code goes here to find the imagetype case
                switch ($typeInt) {
                    case IMG_GIF:
                        $imageType = 'image/gif';
                        break;
                    case IMG_JPG:
                        $imageType = 'image/jpg';
                        break;
                    case IMG_JPEG:
                        $imageType = 'image/jpeg';
                        break;
                    case IMG_PNG:
                        $imageType = 'image/png';
                        break;
                    case IMG_WBMP:
                        $imageType = 'image/wbmp';
                        break;
                    case IMG_XPM:
                        $imageType = 'image/xpm';
                        break;
                    default: 
                        $imageType = 'unknown';
                }
                $mime->addHTMLImage($file_path, $imageType);
            }
        }


        //attachments
        if (is_array($email_attachments)) {
            foreach ($email_attachments as $attachments) {
                $filename = str_replace('uploads/', '', $attachments);
                $attachment = '';
                $file_path = '';
                $type = '';

                if (strpos($filename, '.png') !== false) {
                    $type .= 'image/png';
                }
    
                // ADD attachment(s)
                $attachment1 .= "--$boundary1\r\n";
                $attachment1 .= "Content-Type: $type; name=\"$filename\"\r\n";
                $attachment1 .= "Content-Transfer-Encoding: base64\r\n";
                $attachment1 .= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
                $attachment1 .= "\r\n\r\n";
                $attachment1 .= $attachment;
                $attachment1 .= "\r\n\r\n";

                $body .= $attachment1;
                $mime->addAttachment($file_path, $type);
            }
        }

        // always call these methods in this order
        $mime_params = array(
            'text_encoding' => '7bit',
            'text_charset'  => '"UTF-8"',
            'html_charset'  => '"UTF-8"',
            'head_charset'  => '"UTF-8"'
        );
        //$body = $mime->get(array('text_encoding' => '8bit','html_encoding' => '8bit'));
        $body = $mime->get($mime_params);
        $headers = $mime->headers($headers);

        $smtp_params = array ('host' => $smtp_hostname,
            'port' => $port,
            'auth' => true, // Note 1
            'username' => $username,
            'password' => $password);

        $smtp = Mail::factory('smtp', $smtp_params);
        $mail = $smtp->send($to, $headers, $body);
        

        if (PEAR::isError($mail)) 
        {
            echo("<p>" . $mail->getMessage() . "</p>");
        }
        else 
        {
            echo("<p>Email has been sent!</p>");
            $response = array("success"=>$success);
            echo json_encode($response);
        }
    }
}

 

Do you know why the images wont show up on yahoo and gmail when I send the images as attachment?

I have checked on the image path and i have put the correct image path so it should work fine.

If you can be able to test it for me to find out why the images wont display and if you fix the issue, please let me know what change I need to make so I will try it out.

 

Any advice would be much appreciated.

Thanks in advance.

gmail.png

gmail1.png

yahoo.png

Edited by mark107
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.