[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

embed image php mail()

Posted on 2012-08-29
13
Medium Priority
?
3,697 Views
Last Modified: 2012-10-11
related question:

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_27840780.html

want to embed (not attach)
image
using
php mail (not phpmailer())

I also can not use a mailing list program (constant contact, sendgrid) for this project
0
Comment
Question by:rgb192
  • 6
  • 4
  • 3
13 Comments
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 38347949
With email and images, you can only do one of two things:

A. Insert a REFERENCE to an image that is hosted at a remote URL:
From: me@gr8gonzo.com
To: you@rgb192.com
Subject: An example of MIME email and remote images
Mime-Version: 1.0
Content-Type: multipart/related; boundary="emailsectionseparator"; type="text/html"

--emailsectionseparator
Content-Type: text/html; charset="US-ASCII"

Here is some HTML content:
<img src="http://www.remotedomain.com/image.jpg">

--emailsectionseparator--

Open in new window


or

B. Attach the image to the e-mail and display it using a local reference:
From: me@gr8gonzo.com
To: you@rgb192.com
Subject: An example of MIME email and embedded/attached images
Mime-Version: 1.0
Content-Type: multipart/related; boundary="emailsectionseparator"; type="text/html"

--emailsectionseparator
Content-Type: text/html; charset="US-ASCII"

Here is some HTML content:
<IMG SRC="cid:my50kphoto">

--emailsectionseparator
Content-ID: <my50kphoto>
Content-Type: image/jpeg
Content-Transfer-Encoding: Base64

ABX1JKADFjkad91/291... 50k of base64 data here...

--emailsectionseparator--

Open in new window


Those are your only two options with email.
0
 

Author Comment

by:rgb192
ID: 38348560
I dont understand example B
could you put in code that I could run please
0
 
LVL 36

Accepted Solution

by:
Loganathan Natarajan earned 2000 total points
ID: 38348672
There are few examples how you can do with phpmailer. check out please,

http://www.techportal.co.za/php/152-how-to-embed-images-using-phpmailer
http://www.devraju.com/php/how-to-embed-images-with-php-

Mostly, you can do with, $mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

also, http://phpmailer.worxware.com/index.php?pg=tutorial#4

mailer-class/
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 38348673
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 38350383
Trying to do it raw from mail() is a little hard because of the order in which things happen. It -IS- possible, though. I wrote up a quick class to make it happen. The end result is that it goes out through mail(), though, so you can echo the parts if you want to see how you would write it:

<?php
$Mail = new Gr8GonzosMailWrapper("rgb192@somewhere.com","Test Subject");
$Mail->setBody("Hello! Image is below:<br>".$Mail->embedImage("php.gif")."Testing...<br>\n");
$Mail->setFrom("gr8gonzo@somewhereelse.com"); // Optional
$Mail->Send();


class Gr8GonzosMailWrapper
{
  public $from = "";
  public $to = "";
  public $subject = "";
  public $body = "";

  public $boundaryRelated = "";
  public $boundaryMessageTypes = "";
  public $parts = array();

  public function __construct($to,$subject)
  {
    $this->boundaryRelated       = "==========RELATED".time()."==";
    $this->boundaryMessageTypes  = "==========MSGTYPES".time()."==";
    $this->setTo($to);
    $this->setSubject($subject);
  }

  public function Send($displayCommand = true)
  {
    // Build $headers
    $headers = "";
    if($from) $headers .= "From: {$from}\n";
    $headers .= "MIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/related;\n  boundary=\"".$this->boundaryRelated."\"\n";

    // Build structure
    $newbody = "This is a multi-part message in MIME format.\n";
    $newbody .= "--".$this->boundaryRelated . "\n";

    // Build HTML content
    $newbody .= "Content-Type: multipart/alternative;\n  boundary=\"".$this->boundaryMessageTypes."\"\n";
    $newbody .= "MIME-Version 1.0\n\n";
    $newbody .= "--".$this->boundaryMessageTypes."\n";
    $newbody .= $this->body[0] . "\n";
    $newbody .= "MIME-Version 1.0\n\n";
    $newbody .= $this->body[1] . "\n\n";
    $newbody .= "--".$this->boundaryMessageTypes."--\n";

    // Add images
    foreach($this->parts as $part)
    {
      $contentHeader = $part[0];
      $content = $part[1];
      $newbody .= "--".$this->boundaryRelated."\n";
      $newbody .= $contentHeader . "\n\n";
      $newbody .= $content . "\n\n";
    }

    $newbody .= "--".$this->boundaryRelated."--";

    if($displayCommand)
    {
      echo "mail(\"".$this->to."\",\"".$this->subject."\",\"".$newbody."\",\"".$headers."\");\n";
    }

    mail($this->to,$this->subject,$newbody,$headers);
  }

  public function setTo($address) { $this->to = trim($address); }
  public function setFrom($address) { $this->from = trim($address); }
  public function setSubject($content) { $this->subject = trim($content); }
  public function setBody($content) { 
    $this->body = array("Content-Type: text/html; charset=\"UTF-8\"",trim($content));
  }

  public function embedImage($image,$cid = "")
  { 
    $data = file_get_contents($image);
    $name = basename($image);
    if($cid == "") $cid = preg_replace("/[^a-zA-Z0-9]/","_",$name);
    if(strpos($cid,"@") == false) $cid .= "@gr8gonzosmailwrapper";
    $this->parts[] = array(
      "Content-Type: ".mime_content_type($image)."; name=\"$name\"\n" . 
      "Content-Transfer-Encoding: base64\n" . 
      "Content-ID: <{$cid}>\n" . 
      "Content-Disposition: attachment;\n" . 
      " filename=\"$name\"", 
      chunk_split( base64_encode($data), 68, "\n")); 
    return "<img src=\"cid:{$cid}\">"; 
  }
}

?>

Open in new window

0
 

Author Comment

by:rgb192
ID: 38352152
tried on two servers

Fatal error: Call to undefined function mime_content_type()  on line 82
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 38352557
Throw this onto the end of the script:

if(!function_exists('mime_content_type')) {

    function mime_content_type($filename) {

        $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        $ext = strtolower(array_pop(explode('.',$filename)));
        if (array_key_exists($ext, $mime_types)) {
            return $mime_types[$ext];
        }
        elseif (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $filename);
            finfo_close($finfo);
            return $mimetype;
        }
        else {
            return 'application/octet-stream';
        }
    }
}

Open in new window

0
 

Author Comment

by:rgb192
ID: 38353022
same error


Fatal error: Call to undefined function mime_content_type()  on line 82
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 38353040
@ rgb192

Please do try with phpmailer with it. I gave ref. links how to do.
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 38354172
If you are still getting that error, then something went wrong when you pasted in that code. Can you show us the whole script so far?
0
 

Author Comment

by:rgb192
ID: 38358275
<?php

$Mail = new Gr8GonzosMailWrapper("me@gmail.com","Test Subject");

$Mail->setBody("Hello! Image is below:<br>".$Mail->embedImage("php.gif")."Testing...<br>\n");

$Mail->setFrom("me@gmail.com"); // Optional

$Mail->Send();





class Gr8GonzosMailWrapper

{

  public $from = "";

  public $to = "";

  public $subject = "";

  public $body = "";



  public $boundaryRelated = "";

  public $boundaryMessageTypes = "";

  public $parts = array();



  public function __construct($to,$subject)

  {

    $this->boundaryRelated       = "==========RELATED".time()."==";

    $this->boundaryMessageTypes  = "==========MSGTYPES".time()."==";

    $this->setTo($to);

    $this->setSubject($subject);

  }



  public function Send($displayCommand = true)

  {

    // Build $headers

    $headers = "";

    if($from) $headers .= "From: {$from}\n";

    $headers .= "MIME-Version: 1.0\n";

    $headers .= "Content-Type: multipart/related;\n  boundary=\"".$this->boundaryRelated."\"\n";



    // Build structure

    $newbody = "This is a multi-part message in MIME format.\n";

    $newbody .= "--".$this->boundaryRelated . "\n";



    // Build HTML content

    $newbody .= "Content-Type: multipart/alternative;\n  boundary=\"".$this->boundaryMessageTypes."\"\n";

    $newbody .= "MIME-Version 1.0\n\n";

    $newbody .= "--".$this->boundaryMessageTypes."\n";

    $newbody .= $this->body[0] . "\n";

    $newbody .= "MIME-Version 1.0\n\n";

    $newbody .= $this->body[1] . "\n\n";

    $newbody .= "--".$this->boundaryMessageTypes."--\n";



    // Add images

    foreach($this->parts as $part)

    {

      $contentHeader = $part[0];

      $content = $part[1];

      $newbody .= "--".$this->boundaryRelated."\n";

      $newbody .= $contentHeader . "\n\n";

      $newbody .= $content . "\n\n";

    }



    $newbody .= "--".$this->boundaryRelated."--";



    if($displayCommand)

    {

      echo "mail(\"".$this->to."\",\"".$this->subject."\",\"".$newbody."\",\"".$headers."\");\n";

    }



    mail($this->to,$this->subject,$newbody,$headers);

  }



  public function setTo($address) { $this->to = trim($address); }

  public function setFrom($address) { $this->from = trim($address); }

  public function setSubject($content) { $this->subject = trim($content); }

  public function setBody($content) { 

    $this->body = array("Content-Type: text/html; charset=\"UTF-8\"",trim($content));

  }



  public function embedImage($image,$cid = "")

  { 

    $data = file_get_contents($image);

    $name = basename($image);

    if($cid == "") $cid = preg_replace("/[^a-zA-Z0-9]/","_",$name);

    if(strpos($cid,"@") == false) $cid .= "@gr8gonzosmailwrapper";

    $this->parts[] = array(

      "Content-Type: ".mime_content_type($image)."; name=\"$name\"\n" . 

      "Content-Transfer-Encoding: base64\n" . 

      "Content-ID: <{$cid}>\n" . 

      "Content-Disposition: attachment;\n" . 

      " filename=\"$name\"", 

      chunk_split( base64_encode($data), 68, "\n")); 

    return "<img src=\"cid:{$cid}\">"; 

  }

}







if(!function_exists('mime_content_type')) {



    function mime_content_type($filename) {



        $mime_types = array(



            'txt' => 'text/plain',

            'htm' => 'text/html',

            'html' => 'text/html',

            'php' => 'text/html',

            'css' => 'text/css',

            'js' => 'application/javascript',

            'json' => 'application/json',

            'xml' => 'application/xml',

            'swf' => 'application/x-shockwave-flash',

            'flv' => 'video/x-flv',



            // images

            'png' => 'image/png',

            'jpe' => 'image/jpeg',

            'jpeg' => 'image/jpeg',

            'jpg' => 'image/jpeg',

            'gif' => 'image/gif',

            'bmp' => 'image/bmp',

            'ico' => 'image/vnd.microsoft.icon',

            'tiff' => 'image/tiff',

            'tif' => 'image/tiff',

            'svg' => 'image/svg+xml',

            'svgz' => 'image/svg+xml',



            // archives

            'zip' => 'application/zip',

            'rar' => 'application/x-rar-compressed',

            'exe' => 'application/x-msdownload',

            'msi' => 'application/x-msdownload',

            'cab' => 'application/vnd.ms-cab-compressed',



            // audio/video

            'mp3' => 'audio/mpeg',

            'qt' => 'video/quicktime',

            'mov' => 'video/quicktime',



            // adobe

            'pdf' => 'application/pdf',

            'psd' => 'image/vnd.adobe.photoshop',

            'ai' => 'application/postscript',

            'eps' => 'application/postscript',

            'ps' => 'application/postscript',



            // ms office

            'doc' => 'application/msword',

            'rtf' => 'application/rtf',

            'xls' => 'application/vnd.ms-excel',

            'ppt' => 'application/vnd.ms-powerpoint',



            // open office

            'odt' => 'application/vnd.oasis.opendocument.text',

            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',

        );



        $ext = strtolower(array_pop(explode('.',$filename)));

        if (array_key_exists($ext, $mime_types)) {

            return $mime_types[$ext];

        }

        elseif (function_exists('finfo_open')) {

            $finfo = finfo_open(FILEINFO_MIME);

            $mimetype = finfo_file($finfo, $filename);

            finfo_close($finfo);

            return $mimetype;

        }

        else {

            return 'application/octet-stream';

        }

    }

}





?>

Open in new window






>>
Please do try with phpmailer with it. I gave ref. links how to do.

I can not use phpmailer because shared hosting companies (godaddy and 1and1 will not work with gmail authentication).  I would like to send phpmailer without username,password

$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 465;                   // set the SMTP port for the GMAIL server
$mail->Username   = "gmail@gmail.com";  // GMAIL username
$mail->Password   = "password";            // GMAIL password
0
 

Author Comment

by:rgb192
ID: 38424074
i am still getting the error with php mail()
0
 

Author Closing Comment

by:rgb192
ID: 38488849
when I do not use gmail,
this works, thanks
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month19 days, 3 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question