php mail com imagens

bpalhares

Power Member
Boas

Basicamente, o meu problema é o seguinte:

Estou a criar dinamicamente uma página, com conteudos em texto e imagens e queria agarrar nessa página e criar um mail exactamente igual.

Até agora, o texto segue com a formataçao da pagina correcta, mas as imagens não vão....

É necessario enviá-las como attachment? Se sim, alguém me sabe dizer como?


Agradecido
 
É necessario enviá-las como attachment? Se sim, alguém me sabe dizer como?
Essa é uma possibilidade. Mas não devias fazer isso. Repara: se envias 1.000 e-mails cada um com 100Kb de imagens em anexo, estás na prática a enviar ~100Mbs. É preferível teres as imagens online e no e-mail teres apenas <img src='http://teusite.com/imgs/imgx.png' />.
 
Essa seria uma boa solução, mas a empresa não a quer... a ideia é mandar um relatorio mensal de actividade para os colaboradores, e nesse relatorio está o logo da empresa....

Terei mesmo de por o logo como anexo, o que em termos de trafego nao me preocupa porque sao poucos kb.... só que não faço a minima ideia de como isso se faz...
 
Ter um site na net é muito simples, aliás, para aquilo que tu pedes nem é preciso ter site, basta fazer o upload do ficheiro ou imagem para uma conta de alojamento e depois associar o link à tua página, tal como já foi aqui dito e ficas com o teu problema resolvido.

Nada mais simples.:cool:
 
Usa este código..

P.S. Não sou o autor.

PHP:
<?php

  /*
   *  Class mime_mail
   *  Original implementation by Sascha Schumann <[email protected]>
   *  Modified by Tobias Ratschiller <[email protected]>:
   *      - general code clean-up
   *      - separate body- and from-property
   *      - killed some mostly un-necessary stuff
   *  Modified by Patrick Polzer <[email protected]>:
   *      - added "Content-Disposition"-MIME-Statement for all attachments
   *        (does not affect body text)
   */

  class mime_mail
   {
   var $parts;
   var $to;
   var $from;
   var $headers;
   var $subject;
   var $body;

   /*
    *     void mime_mail()
    *     class constructor
    */
   function mime_mail()
    {
    $this->parts = array();
    $this->to = "";
    $this->from = "";
    $this->subject = "";
    $this->body = "";
    $this->headers = "";
    }

   /*
    *     void add_attachment(string message, [string name], [string ctype])
    *     Add an attachment to the mail object
    */
   function add_attachment($message, $name = "", $ctype = "application/octet-stream")
    {
    $this->parts[] = array (
                            "ctype" => $ctype,
                            "message" => $message,
                            "encode" => $encode,
                            "name" => $name
                            );
    }

  /*
   *      void build_message(array part=
   *      Build message parts of an multipart mail
   */
  function build_message($part)
   {
   $message = $part["message"];
   $message = chunk_split(base64_encode($message));
   $encoding = "base64";
   if ($part["name"]!="") {
      $dispstring = "Content-Disposition: attachment; filename=\"$part[name]\"\n";
   }
   return "Content-Type: ".$part["ctype"].
                          ($part["name"]?"; name = \"".$part["name"]."\"" : "").
                          "\nContent-Transfer-Encoding: $encoding\n".$dispstring."\n$message\n";
   }

  /*
   *      void build_multipart()
   *      Build a multipart mail
   */
  function build_multipart()
   {
   $boundary = "b".md5(uniqid(time()));
   $multipart = "Content-Type: multipart/mixed; boundary=$boundary\n\nThis is a MIME encoded message.\n\n--$boundary";

   for($i = sizeof($this->parts)-1; $i >= 0; $i--)
      {
      $multipart .= "\n".$this->build_message($this->parts[$i])."--$boundary";
      }
   return $multipart.= "--\n";
   }

  /*
   *      void send()
   *      Send the mail (last class-function to be called)
   */
  function send()
   {
   $mime = "";
   if (!empty($this->from))
      $mime .= "From: ".$this->from."\n";
   if (!empty($this->headers))
      $mime .= $this->headers."\n";

   if (!empty($this->body))
      $this->add_attachment($this->body, "", "text/html");//text/plain
   $mime .= "MIME-Version: 1.0\n".$this->build_multipart();
   $success = mail($this->to, $this->subject, "", $mime);
   if (!$success) {
        echo '<h2>Mail: Warning, mail could not be sent</h2>';
   } else {
        echo '<h2>Mail: Mail successfully sent to '.$this->to;
   }
   }
  }; // end of class

  /*
   * Example usage
   *

   $attachment = fread(fopen("aqua.jpg", "r"), filesize("aqua.jpg"));

   $mail = new mime_mail();
   $mail->from = "[email protected]";
   $mail->headers = "Errors-To: [email protected]";
   $mail->to = "[email protected]";
   $mail->subject = "Testing...";
   $mail->body = "
   
       <table>
           <tr>
               <th>Hier ist ein Bild</th>
               <th>Hier ist noch ein Bild</th>
           </tr>
           <tr>
               <td><img src='test.jpg' wight = '100px'></td>
               <td><img src='test.jpg' wight = '100px'></td>
           </tr>
       </table>   
   
   ";
   $mail->add_attachment("$attachment", "test.jpg", "image/jpeg");
   $mail->send();

   */
?>
 
Usa este código..

P.S. Não sou o autor.

PHP:
<?php
 
  /*
   *  Class mime_mail
   *  Original implementation by Sascha Schumann <[email protected]>
   *  Modified by Tobias Ratschiller <[email protected]>:
   *      - general code clean-up
   *      - separate body- and from-property
   *      - killed some mostly un-necessary stuff
   *  Modified by Patrick Polzer <[email protected]>:
   *      - added "Content-Disposition"-MIME-Statement for all attachments
   *        (does not affect body text)
   */
 
  class mime_mail
   {
   var $parts;
   var $to;
   var $from;
   var $headers;
   var $subject;
   var $body;
 
   /*
    *     void mime_mail()
    *     class constructor
    */
   function mime_mail()
    {
    $this->parts = array();
    $this->to = "";
    $this->from = "";
    $this->subject = "";
    $this->body = "";
    $this->headers = "";
    }
 
   /*
    *     void add_attachment(string message, [string name], [string ctype])
    *     Add an attachment to the mail object
    */
   function add_attachment($message, $name = "", $ctype = "application/octet-stream")
    {
    $this->parts[] = array (
                            "ctype" => $ctype,
                            "message" => $message,
                            "encode" => $encode,
                            "name" => $name
                            );
    }
 
  /*
   *      void build_message(array part=
   *      Build message parts of an multipart mail
   */
  function build_message($part)
   {
   $message = $part["message"];
   $message = chunk_split(base64_encode($message));
   $encoding = "base64";
   if ($part["name"]!="") {
      $dispstring = "Content-Disposition: attachment; filename=\"$part[name]\"\n";
   }
   return "Content-Type: ".$part["ctype"].
                          ($part["name"]?"; name = \"".$part["name"]."\"" : "").
                          "\nContent-Transfer-Encoding: $encoding\n".$dispstring."\n$message\n";
   }
 
  /*
   *      void build_multipart()
   *      Build a multipart mail
   */
  function build_multipart()
   {
   $boundary = "b".md5(uniqid(time()));
   $multipart = "Content-Type: multipart/mixed; boundary=$boundary\n\nThis is a MIME encoded message.\n\n--$boundary";
 
   for($i = sizeof($this->parts)-1; $i >= 0; $i--)
      {
      $multipart .= "\n".$this->build_message($this->parts[$i])."--$boundary";
      }
   return $multipart.= "--\n";
   }
 
  /*
   *      void send()
   *      Send the mail (last class-function to be called)
   */
  function send()
   {
   $mime = "";
   if (!empty($this->from))
      $mime .= "From: ".$this->from."\n";
   if (!empty($this->headers))
      $mime .= $this->headers."\n";
 
   if (!empty($this->body))
      $this->add_attachment($this->body, "", "text/html");//text/plain
   $mime .= "MIME-Version: 1.0\n".$this->build_multipart();
   $success = mail($this->to, $this->subject, "", $mime);
   if (!$success) {
        echo '<h2>Mail: Warning, mail could not be sent</h2>';
   } else {
        echo '<h2>Mail: Mail successfully sent to '.$this->to;
   }
   }
  }; // end of class
 
  /*
   * Example usage
   *
 
   $attachment = fread(fopen("aqua.jpg", "r"), filesize("aqua.jpg"));
 
   $mail = new mime_mail();
   $mail->from = "[email protected]";
   $mail->headers = "Errors-To: [email protected]";
   $mail->to = "[email protected]";
   $mail->subject = "Testing...";
   $mail->body = "
 
       <table>
           <tr>
               <th>Hier ist ein Bild</th>
               <th>Hier ist noch ein Bild</th>
           </tr>
           <tr>
               <td><img src='test.jpg' wight = '100px'></td>
               <td><img src='test.jpg' wight = '100px'></td>
           </tr>
       </table>   
 
   ";
   $mail->add_attachment("$attachment", "test.jpg", "image/jpeg");
   $mail->send();
 
   */
?>


Humm...

O que faz este código?
Onde se pode usar?:confused:
 
Esse é um codigo de php para enviar mails.

Podes mete-lo no bloco de notas e depois guarda-lo em extensão .php
ex: newsletter.php

Necessita de alojamento num servidor configurado com php para o conseguir enviar, tens de entender um bocadinho o código para meteres la os dados que faltam e na parte onde ta o html só, é onde vais meter a tua newsletter. Está tudo nesse code;)
 
Isto pode dar jeito...:009:

Mas eu acho que não resolve o problema em questão, teremos que continuar a anexar as imagens ao ficheiro ou então teremos que alojá-las num servidor, né?


Cumps
 
Última edição:
É melhor ficar no servidor as imagens e com o codigo de html fazeres com que vá buscar as imagens ao servidor.

Tambem esqueci de referir que precisas de dominio e um mail do dominio, por ex: [email protected]
e tem de estar bem configurado no codigo de php para que tudo funcione bem.

Espero que tenha ajudado
 
Esse realmente já é muito bom.

Eu estive a ver a bocadinho este link e achei o script bastante interessante e muito completo. Existem vários scripts na internet para fazer esta tarefa, é uma questão de escolheres um, ou então fazeres o teu proprio.

Isso tens de ser tu a decidir. ;)
 
Humm...

O que faz este código?
Onde se pode usar?:confused:

Se tivesses lido um bocadinho do código ias encontrar algo como:

PHP:
$attachment = fread(fopen("aqua.jpg", "r"), filesize("aqua.jpg"));

Não é dificil de entender..

Ah, e para obter este código bastou escrever 'php mail with attachments' no google.
 
Back
Topo