HTML email shows as text plain

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • matheussousuke
    New Member
    • Sep 2009
    • 249

    HTML email shows as text plain

    I'm having trouble with e-mail sending, I mean, the website is suposed to send a confirmation email after sign up, but it gets like text plain instead of HTML

    May someone help me, please?

    Here's the code

    Code:
    <?php
    
    
    require_once 'path_cnfg.php';
    
    require_once(path_cnfg('pathToLibDir').'func_common.php');
    require_once(path_cnfg('pathToLibDir').'func_checkUser.php');
    require_once(path_cnfg('pathToCnfgDir').'cnfg_vars.php');
    require_once(path_cnfg('pathToLibDir').'vars_gbl.php');
     
    $myDB = db_connect();
     
    $cookie = $HTTP_COOKIE_VARS['log_in_cookie'];
    
    $content = array();
    
    $submit = $HTTP_POST_VARS["submit"];
    
    if ( !checkUser('', '') )
    {   if ( $submit && $submit != 'validate' && checkForm() )
        {   $gbl["try_register"] = true;
            if ( prelim_insert() )
            {   $gbl["register_message"] = 'Um código de registro foi enviado para seu endereço de email.<BR>Siga as instruções no email para verificar seu registro.<BR>' ; 
            }
            else
            {   $gbl["register_message"] = 'O registro preliminar falhou.<BR>'.$gbl["register_message"];
            } 
        }
      
    }
    
    
    if ($gbl["loggedIn"])
    {   $content[] = "echo 'Você já está logado no sistema.';";
    }
    elseif (!$submit)
    {   $content[] = "echo 'Apenas números, letras, e o caractere underline( _ ) são permitidos no nome de usuário.<BR>';";
        $content[] = 'doForm();';
    }
    elseif ($gbl["errors"]!="")
    {   $content[] = "echo '<font class=\"errorBig\">Erros:<BR></font>';";
        $content[] = "echo '<font class=\"errorLittle\">';" ;
        $content[] = 'echo $gbl["errors"] ;' ;
        $content[] = 'echo "</font><BR>";' ;
        #echo $content[(count($content)-1)]."<BR>";
        $content[] = 'doForm();';
    } 
    elseif ($gbl["try_register"])
    {   $content[] = 'echo $gbl["register_message"];';
    }
    
    // This line brings in the template file.
    // If you want to use a different template file 
    // simply change this line to require the template 
    // file that you want to use.
    require_once(path_cnfg('pathToTemplatesDir').cnfg('tmplt_register'));
    
    db_disconnect($myDB);
    
    
    # --- START FUNCTIONS ---
    
    
    // *********** START FUNCTION prelim_insert() *************
    
    function prelim_insert()
    { 
        GLOBAL $gbl, $myDB, $HTTP_POST_VARS ;
    
        $new_user_name = $HTTP_POST_VARS["new_user_name"];
        $email = $HTTP_POST_VARS["email"];
        $password1 = $HTTP_POST_VARS["password1"];
    
    
        $query = "SELECT user_name FROM std_users 
                  WHERE user_name='$new_user_name'";
    
        $result = mysql_query($query, $myDB);
    
        if (mysql_num_rows($result) > 0)
        {   $gbl["register_message"] .= 'Sinto muito, mas este nome de usuário já está sendo usado, por favor digite outro nome.<BR>';
            return false;
        }
    
        srand((double)microtime()*1000000);
    
        $the_rand = rand(1, 10000);
        $the_rand2 = rand(1, 10000);
        $the_rand3 = rand(1, 10000);
    
        $the_rand = ''.$the_rand.''.$the_rand2.''.$the_rand3;
    
        $query = "INSERT INTO std_temp_users(user_name, password, email, sign_up_date, prelim_rand) VALUES('$new_user_name', '$password1', '$email', ".time().", '$the_rand')";
    
        $result = mysql_query($query, $myDB);
    
        if (!$result) 
        {   if ( preg_match("/duplicate entry/i", mysql_error()) )
            {   $gbl["errors"] .= "Por favor digite outro nome de usuário.<BR>
                                    Este já está em uso.";
            }
    
            return false;
        }
    
        $to = $email;
        $subject = 'Seu cadastro';
    
        $the_link = cnfg('deDir').'verify_registration.php';
    
        $message = '<html><body>
    
    
    
        Por favor siga estas instruções para verificar seu registro:
        <BR>
        1. Clique no link abaixo:
        <BR>
        2. Digite o usuário e o código de confirmação que está localizado abaixo desta linha.
        <BR>
        <BR>
        Observação: Após verificar seu cadastro você fará login no site usando o nome usuário e senha  que você cadastrou. 
        <BR>
        O código de confirmação é usado apenas para confirmar o seu cadastro.
        <BR>
        <BR>
        Username: '.$new_user_name.'
        <BR>
        Código de confirmação:  '.$the_rand.'
        <BR>
        <BR>
         ' ;
    
        $message .= "<a href=\"$the_link\">$the_link</a>";
    
        $message .= '</body></html>';
    
    
        #$headers = "MIME-Version: 1.0\r\n";
        #$headers .= "Return-Path: <".cnfg('replyEmail').">\r\n";
        #$headers .= "X-Sender: <".cnfg('replyEmail').">\r\n"; 
        #$headers .= "X-Mailer: PHP\r\n"; // mailer
        $headers .= "De: <".cnfg('replyEmail').">".$gbl['newLine'];
        $headers .= "Responder para: <".cnfg('replyEmail').">".$gbl['newLine'];
        $headers .= "tipo de conteúdo: text/html; charset=iso-8859-1".$gbl['newLine'];
    
    
        if ($result) 
        {   if ( mail($to, $subject, $message, $headers) )
            {   return true;
            }
    	    else
    	    {   echo 'erro ao enviar email<BR>';
    		    return false;
    	    }
        }
        else 
        {   return false;
        }
    
    } // end function prelim_insert()
    
    // *********** END FUNCTION prelim_insert() *************
    
    
    // *********** START FUNCTION doForm() *************
    
    function doForm()
    {
        GLOBAL $HTTP_POST_VARS ;
    
        $new_user_name = $HTTP_POST_VARS["new_user_name"];
        $password1 = $HTTP_POST_VARS["password1"];
        $password2 = $HTTP_POST_VARS["password2"];
        $email = $HTTP_POST_VARS["email"];
      
        if (!$submit || $errors!="")
        {
            ?>
    
    
            <FORM ACTION="<?php echo cnfg('deDir'); ?>register.php" METHOD="POST">
            <table width="741" border="0" cellpadding="0" cellspacing="0">
              <!--DWLayoutTable-->
            <BR>
            <tr><td height="22" colspan="4" align="right" valign="top"> Nome de usuário: </td>
            <td colspan="3" align="left" valign="baseline">
              <INPUT TYPE="TEXT" NAME="new_user_name" value="<?php echo $new_user_name; ?>" SIZE="15">        </td>
            <td colspan="2" rowspan="2" valign="top"><div align="center"><strong>Embora este site seja seguro, não é possível evitar tentativas de invasão de hackers, por favor, evite usar senhas pessoais, como por exemplo, senhas de email.</strong></div></td>
            <td width="1"></td>
            </tr>
            <tr><td colspan="4" rowspan="2" align="right" valign="top">
            Senha:
            </td>
            <td colspan="3" rowspan="2" align="left" valign="baseline">
              <INPUT TYPE="PASSWORD" NAME="password1" value="<?php echo $password1; ?>" SIZE="15">        </td>
            <td height="16"></td>
            </tr>
            <tr>
              <td width="57" height="6"></td>
              <td width="317"></td>
              <td></td>
            </tr>
            <tr><td height="22" colspan="4" align="right" valign="top">
            Digite sua senha novamente:
            </td>
            <td colspan="3" align="left" valign="baseline">
              <INPUT TYPE="PASSWORD" NAME="password2" value="<?php echo $password2; ?>" SIZE="15">        </td>
            <td></td>
            <td></td>
            <td></td>
            </tr>
            
            
            
            <tr><td height="19" colspan="4" align="right" valign="top"> Endereço de Email: </td>
            <td colspan="3" rowspan="2" align="left" valign="baseline">
              <INPUT TYPE="TEXT" NAME="email" value="<?php echo $email; ?>" SIZE="15">        </td>
            <td></td>
            <td></td>
            <td></td>
            </tr>
            <tr>
              <td width="76" height="3"></td>
              <td width="119"></td>
              <td width="49"></td>
              <td width="32"></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td height="24"></td>
              <td></td>
              <td></td>
              <td colspan="2" valign="top"><input type="SUBMIT" name="submit" value="Enviar" /></td>
              <td width="39">&nbsp;</td>
              <td width="32">&nbsp;</td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td height="14"></td>
              <td></td>
              <td></td>
              <td></td>
              <td width="19"></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td height="19"></td>
              <td></td>
              <td colspan="4" valign="top"><p><strong>Termos de utiliza&ccedil;&atilde;o</strong></p></td>
              <td>&nbsp;</td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td height="17"></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td height="163"></td>
              <td colspan="7" valign="top"><textarea name="textarea" cols="55" rows="10">Apesar dos administradores deste site tentarem remover ou editar qualquer material indesejável logo que detectado, é impossível rever todos os anúncios. Como tal você reconhece por este meio que todos os anúncios colocados no site expressam os pontos de vista e opiniões dos seus respectivos autores e não dos administradores, moderadores ou o encarregado das páginas (exceto anúncios colocados por essas pessoas) não sendo por tais responsáveis.
    
    Você aceita não colocar qualquer mensagem ou imagem abusiva, obscena, invulgar, insultuosa, de ódio, ameaçadora, sexualmente tendenciosa ou qualquer outro material que possa violar qualquer lei em vigor, como por exemplo, pedofilia e racismo. Se tal acontecer isso irá conduzir à sua expulsão imediata e permanente (além de ser notificado o seu fornecedor de Internet). Você concorda que quem faz e mantém estas páginas, administradores deste site têm o direito de remover, editar, mover ou encerrar qualquer anúncio em qualquer altura que eles assim o entendam e seja implícito. Como utilizador você aceita que qualquer informação que forneceu acima seja guardada numa base de dados. Apesar dessa informação não ser fornecida a terceiros sem a sua autorização, o encarregado das páginas, administradores não podem assumir a responsabilidade por qualquer tentativa de ato de "hacking" (intromissão forçada e ilegal que conduza a essa informação ser exposta). 
    
    Este sistema de anúncios usa "cookies" para guardar informação no seu computador. Esses "cookies" não possuem nenhuma das informações acima fornecidas, apenas serve para melhorar o seu prazer a quando e enquanto visita este site. O endereço de e-mail é apenas usado para confirmar a informação do seu registro e a senha (bem como para enviar novas senhas caso se esqueça da que acabou de submeter). 
    
    Ao clicar em “Enviar”, você concorda com as condições impostas nos Termos de Utilização.</textarea></td>
              <td>&nbsp;</td>
              <td></td>
            </tr>
            <tr>
              <td height="35"></td>
              <td>&nbsp;</td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            </table>
    
            </FORM>
    
            <?php 
    
        } // end if
    
    } // end function doForm()
    
    // *********** END FUNCTION doForm() *************
    
    // *********** START FUNCTION checkForm() *************
    function checkForm()
    {
        GLOBAL $gbl, $HTTP_POST_VARS ;
    
    
        $new_user_name = $HTTP_POST_VARS['new_user_name'];
        $password1 = $HTTP_POST_VARS['password1'];
        $password2 = $HTTP_POST_VARS['password2'];
        $email = $HTTP_POST_VARS['email'];
        $submit = $HTTP_POST_VARS['submit'];
    
        if ($submit)
        {   if ($new_user_name)
            {   if ( preg_match("/[^0-9a-zA-Z_]/", $new_user_name ) )
                {   $gbl['errors'] .= '• Invalid characters<BR>' ;
                    $new_user_name='';
                }
    
                if ( (strlen($new_user_name) < cnfg('userNameMinLength') )
                     || (strlen($new_user_name) > cnfg('userNameMaxLength') ) )
                {   $gbl['errors'] .= '• Nomes de usuários devem ter menos de ';
                    $gbl['errors'] .= cnfg('userNameMaxLength').', e mais de ';
                    $gbl['errors'] .= cnfg('userNameMinLength').' caracteres.<BR>'; 
                }
    
    
            }
            else
            {   $gbl['errors'] .= '• Você não digitou um nome de usuário.<BR>';
            }
    
    
            if($password1 && $password2)
            {   if($password1 != $password2)
                {   $gbl['errors'] .= '• As senhas digitadas não correspondem uma a outra<BR>';
                    $password1 = ''; 
                    $password2 = '';
                }
    
                if ( (strlen($password1) < cnfg('userPassMinLength') )
                     || (strlen($password1) > cnfg('userPassMaxLength') ) )
                {   $gbl['errors'] .= '• Senhas devem ter menos de ';
                    $gbl['errors'] .= cnfg('userPassMaxLength').', e mais de ';
                    $gbl['errors'] .= cnfg('userPassMinLength').' caracteres.<BR>';
                }
            }
            else
            {   $gbl['errors'] .= '• Você precisa digitar uma senha.<BR>';
                $password1 = ''; 
                $password2 = '';
            }
    
    
            if ($email)
            {   if ( !preg_match("/([\w\-\.])+@([\w\-\.])+\.([a-zA-Z])+/i", $email) )
                {   $gbl['errors'] .= '• Endereço de e-mail inexistente.<BR>';
                    $email = '';
                }
            }
            else
            {   $gbl['errors'] .= '• Você precisa digitar um endereço de email.<BR>';
            }
        } // end if($submit) 
    
    
        if ($gbl['errors'] != '')
        {   return false; 
        }
        else
        {   return true; 
        }
    
    } // end function checkForm()
    
    // *********** END FUNCTION checkForm() *************
    
    ?>
  • matheussousuke
    New Member
    • Sep 2009
    • 249

    #2
    This how it appears on the email:




    Code:
    Responder para: <email@example.com>
    tipo de conteúdo: text/html; charset=iso-8859-1
    
    
    <html><body>
    
    
    
        Por favor siga estas instruções para verificar seu registro:
        <BR>
        1. Clique no link abaixo:
        <BR>
        2. Digite o usuário e o código de confirmação que está localizado abaixo desta
    linha.
        <BR>
        <BR>
        Observação: Após verificar seu cadastro você fará login no site usando o nome
    usuário e senha  que você cadastrou. 
        <BR>
        O código de confirmação é usado apenas para confirmar o seu cadastro.
        <BR>
        <BR>
        Username: jackbouer3
        <BR>
        Código de confirmação:  662849454704
        <BR>
        <BR>
         <a
    href="/anuncieaki/verify_registration.php">/anuncieaki/verify_registration.php</a></body></html>

    Comment

    • matheussousuke
      New Member
      • Sep 2009
      • 249

      #3
      Originally posted by matheussousuke
      I'm having trouble with e-mail sending, I mean, the website is suposed to send a confirmation email after sign up, but it gets like text plain instead of HTML

      May someone help me, please?

      Here's the code


      I know the code is a quite long, so I posted the part where I think the error is:
      This:


      Code:
      // *********** START FUNCTION prelim_insert() *************
      
      function prelim_insert()
      { 
          GLOBAL $gbl, $myDB, $HTTP_POST_VARS ;
      
          $new_user_name = $HTTP_POST_VARS["new_user_name"];
          $email = $HTTP_POST_VARS["email"];
          $password1 = $HTTP_POST_VARS["password1"];
      
      
          $query = "SELECT user_name FROM std_users 
                    WHERE user_name='$new_user_name'";
      
          $result = mysql_query($query, $myDB);
      
          if (mysql_num_rows($result) > 0)
          {   $gbl["register_message"] .= 'Sinto muito, mas este nome de usuário já está sendo usado, por favor digite outro nome.<BR>';
              return false;
          }
      
          srand((double)microtime()*1000000);
      
          $the_rand = rand(1, 10000);
          $the_rand2 = rand(1, 10000);
          $the_rand3 = rand(1, 10000);
      
          $the_rand = ''.$the_rand.''.$the_rand2.''.$the_rand3;
      
          $query = "INSERT INTO std_temp_users(user_name, password, email, sign_up_date, prelim_rand) VALUES('$new_user_name', '$password1', '$email', ".time().", '$the_rand')";
      
          $result = mysql_query($query, $myDB);
      
          if (!$result) 
          {   if ( preg_match("/duplicate entry/i", mysql_error()) )
              {   $gbl["errors"] .= "Por favor digite outro nome de usuário.<BR>
                                      Este já está em uso.";
              }
      
              return false;
          }
      
          $to = $email;
          $subject = 'Seu cadastro';
      
          $the_link = cnfg('deDir').'verify_registration.php';
      
          $message = '<html><body>
      
      
      
          Por favor siga estas instruções para verificar seu registro:
          <BR>
          1. Clique no link abaixo:
          <BR>
          2. Digite o usuário e o código de confirmação que está localizado abaixo desta linha.
          <BR>
          <BR>
          Observação: Após verificar seu cadastro você fará login no site usando o nome usuário e senha  que você cadastrou. 
          <BR>
          O código de confirmação é usado apenas para confirmar o seu cadastro.
          <BR>
          <BR>
          Username: '.$new_user_name.'
          <BR>
          Código de confirmação:  '.$the_rand.'
          <BR>
          <BR>
           ' ;
      
          $message .= "<a href=\"$the_link\">$the_link</a>";
      
          $message .= '</body></html>';
      
      
          #$headers = "MIME-Version: 1.0\r\n";
          #$headers .= "Return-Path: <".cnfg('replyEmail').">\r\n";
          #$headers .= "X-Sender: <".cnfg('replyEmail').">\r\n"; 
          #$headers .= "X-Mailer: PHP\r\n"; // mailer
          $headers .= "De: <".cnfg('replyEmail').">".$gbl['newLine'];
          $headers .= "Responder para: <".cnfg('replyEmail').">".$gbl['newLine'];
          $headers .= "tipo de conteúdo: text/html; charset=iso-8859-1".$gbl['newLine'];
      
      
          if ($result) 
          {   if ( mail($to, $subject, $message, $headers) )
              {   return true;
              }
      	    else
      	    {   echo 'erro ao enviar email<BR>';
      		    return false;
      	    }
          }
          else 
          {   return false;
          }
      
      } // end function prelim_insert()
      
      // *********** END FUNCTION prelim_insert() *************

      Comment

      • matheussousuke
        New Member
        • Sep 2009
        • 249

        #4
        Somebody there?
        Somebody there?

        Comment

        • Dormilich
          Recognized Expert Expert
          • Aug 2008
          • 8694

          #5
          Originally posted by matheussousuke
          Somebody there?
          no, we are having our beauty sleep.

          anyways, when it comes to HTML mail, I usually use mail libraries like SwiftMailer which are easier to use than trying to get mail() sending the HTML.

          Comment

          • Atli
            Recognized Expert Expert
            • Nov 2006
            • 5062

            #6
            Hey.

            [code=php] $headers .= "tipo de conteúdo: text/html; charset=iso-8859-1".$gbl['newLine'];[/code]
            I'm pretty sure this is supposed to be in English.
            Have you tried that?

            I understand the need to localize things, but it is usually not a good idea to try to localize the actual code. It's best to leave that in English :-)

            P.S.
            The $HTTP_POST_VARS array was deprecated with PHP 4.1.
            If you are coding in PHP 4.1 or higher, you should be using $_POST instead.
            Last edited by Atli; Nov 20 '09, 10:41 AM. Reason: Added the P.S.

            Comment

            • matheussousuke
              New Member
              • Sep 2009
              • 249

              #7
              Originally posted by Atli
              Hey.

              [code=php] $headers .= "tipo de conteúdo: text/html; charset=iso-8859-1".$gbl['newLine'];[/code]
              I'm pretty sure this is supposed to be in English.
              Have you tried that?

              I understand the need to localize things, but it is usually not a good idea to try to localize the actual code. It's best to leave that in English :-)

              P.S.
              The $HTTP_POST_VARS array was deprecated with PHP 4.1.
              If you are coding in PHP 4.1 or higher, you should be using $_POST instead.

              Well, yeah, I know, it's in portuguese, but there's nothing important to be translated to english, what is in portuguese are things like "Here is your confirmation code", u know, nothing to do to the code, but thanks, I'll follow the advice.

              Let me see if that works using "$_POST".
              thanks again.

              Comment

              • matheussousuke
                New Member
                • Sep 2009
                • 249

                #8
                Originally posted by matheussousuke
                Well, yeah, I know, it's in portuguese, but there's nothing important to be translated to english, what is in portuguese are things like "Here is your confirmation code", u know, nothing to do to the code, but thanks, I'll follow the advice.

                Let me see if that works using "$_POST".
                thanks again.

                Post didn't work. =/

                Comment

                • matheussousuke
                  New Member
                  • Sep 2009
                  • 249

                  #9
                  Originally posted by Dormilich
                  no, we are having our beauty sleep.

                  anyways, when it comes to HTML mail, I usually use mail libraries like SwiftMailer which are easier to use than trying to get mail() sending the HTML.

                  Downloaded it, how do I use it?

                  Comment

                  • Markus
                    Recognized Expert Expert
                    • Jun 2007
                    • 6092

                    #10
                    Originally posted by matheussousuke
                    Well, yeah, I know, it's in portuguese, but there's nothing important to be translated to english, what is in portuguese are things like "Here is your confirmation code", u know, nothing to do to the code, but thanks, I'll follow the advice.

                    Let me see if that works using "$_POST".
                    thanks again.
                    Headers should be sent in English. That is, the header should be: Content-type: text/html;

                    Comment

                    • Dormilich
                      Recognized Expert Expert
                      • Aug 2008
                      • 8694

                      #11
                      Originally posted by matheussousuke
                      Downloaded it, how do I use it?
                      check out SwiftMailer’s documentation, everything is explained there.

                      Comment

                      • matheussousuke
                        New Member
                        • Sep 2009
                        • 249

                        #12
                        Originally posted by Atli
                        Hey.

                        [code=php] $headers .= "tipo de conteúdo: text/html; charset=iso-8859-1".$gbl['newLine'];[/code]
                        I'm pretty sure this is supposed to be in English.
                        Have you tried that?

                        I understand the need to localize things, but it is usually not a good idea to try to localize the actual code. It's best to leave that in English :-)

                        P.S.
                        The $HTTP_POST_VARS array was deprecated with PHP 4.1.
                        If you are coding in PHP 4.1 or higher, you should be using $_POST instead.

                        Oh, sorry, didn see u posted a code. Yeah, that should be in english.

                        Comment

                        • matheussousuke
                          New Member
                          • Sep 2009
                          • 249

                          #13
                          Originally posted by Atli
                          Hey.

                          [code=php] $headers .= "tipo de conteúdo: text/html; charset=iso-8859-1".$gbl['newLine'];[/code]
                          I'm pretty sure this is supposed to be in English.
                          Have you tried that?

                          I understand the need to localize things, but it is usually not a good idea to try to localize the actual code. It's best to leave that in English :-)

                          P.S.
                          The $HTTP_POST_VARS array was deprecated with PHP 4.1.
                          If you are coding in PHP 4.1 or higher, you should be using $_POST instead.



                          There are $HTTP_COOKIE_VA RS, do I have to change it to $POST_VARS ???

                          Comment

                          • Dormilich
                            Recognized Expert Expert
                            • Aug 2008
                            • 8694

                            #14
                            change $HTTP_COOKIE_VA RS to $_COOKIE

                            Comment

                            • matheussousuke
                              New Member
                              • Sep 2009
                              • 249

                              #15
                              headers are in english now, but nothing works.

                              Comment

                              Working...