Results 1 to 37 of 37
  1. #1
    Join Date
    May 2005
    Location
    Gaza, Palestine
    Posts
    25

    Arrow php: simple code to send HTML email

    good day,

    this simple code lines will help you sending html email.
    of course you can enhance for your need eg. using form, using it in newsletter etc.
    but outcoming emails might reported as spam ... so when you test don't forget to check you bulk/junk mail lol..


    PHP Code:
    <?
        
    //change this to your email.
        
    $to "[email protected]";
        
    $from "[email protected]";
        
    $subject "Hello! This is HTML email";

        
    //begin of HTML message
        
    $message = <<<EOF
    <html>
      <body bgcolor="#DCEEFC">
        <center>
            <b>Looool!!! I am reciving HTML email......</b> <br>
            <font color="red">Thanks Mohammed!</font> <br>
            <a href="http://www.maaking.com/">* maaking.com</a>
        </center>
          <br><br>*** Now you Can send HTML Email <br> Regards<br>MOhammed Ahmed - Palestine
      </body>
    </html>
    EOF;
       
    //end of message
        
    $headers  "From: $from\r\n";
        
    $headers .= "Content-type: text/html\r\n";

        
    //options to send to cc+bcc
        //$headers .= "Cc: [email][email protected][/email]";
        //$headers .= "Bcc: [email][email protected][/email]";
        
        // now lets send the email.
        
    mail($to$subject$message$headers);

        echo 
    "Message has been sent....!";
    ?>
    the easy can be hard.
    Mohammed Ahmed - ME. Palestine
    http://www.maaking.com
    Email/MSN: [email protected]

  2. Thread Summary This thread contains 2 different methods of code to send HTML email.

    The first simple php script is included in the first post.
    PHP Code:
    <?
        
    //change this to your email.
        
    $to "[email protected]";
        
    $from "[email protected]";
        
    $subject "Hello! This is HTML email";

        
    //begin of HTML message
        
    $message = <<<EOF
    <html>
      <body bgcolor="#DCEEFC">
        <center>
            <b>Looool!!! I am reciving HTML email......</b> <br>
            <font color="red">Thanks Mohammed!</font> <br>
            <a href="http://www.maaking.com/">* maaking.com</a>
        </center>
          <br><br>*** Now you Can send HTML Email <br> Regards<br>MOhammed Ahmed - Palestine
      </body>
    </html>
    EOF;
       
    //end of message
        
    $headers  "From: $from\r\n";
        
    $headers .= "Content-type: text/html\r\n";

        
    //options to send to cc+bcc
        //$headers .= "Cc: [email][email protected][/email]";
        //$headers .= "Bcc: [email][email protected][/email]";
        
        // now lets send the email.
        
    mail($to$subject$message$headers);

        echo 
    "Message has been sent....!";
    ?>
    The second code uses MIME
    PHP Code:
    <?
        
    //change this to your email.
        
    $to "[email protected]";
        
    $from "[email protected]";
        
    $subject "Hello! This is HTML email";

        
    //begin of HTML message
        
    $message "<html>
      <body bgcolor=\"#DCEEFC\">
        <center>
            <b>Looool!!! I am reciving HTML email......</b> <br>
            <font color=\"red\">Thanks Mohammed!</font> <br>
            <a href=\"http://www.maaking.com/\">* maaking.com</a>
        </center>
          <br><br>*** Now you Can send HTML Email <br> Regards<br>MOhammed Ahmed - Palestine
      </body>
    </html>"
    ;
       
    //end of message

        // To send the HTML mail we need to set the Content-type header.
        
    $headers "MIME-Version: 1.0rn";
        
    $headers .= "Content-type: text/html; charset=iso-8859-1rn";
        
    $headers  .= "From: $from\r\n";
        
    //options to send to cc+bcc
        //$headers .= "Cc: [email][email protected][/email]";
        //$headers .= "Bcc: [email][email protected][/email]";
        
        // now lets send the email.
        
    mail($to$subject$message$headers);

        echo 
    "Message has been sent....!";
    ?>
    For either code, simply update the details to what you need. EXAMPLE: me @ MY domain dot com

    Contributors: SoftWareRevue

  3. #2
    Join Date
    May 2005
    Location
    Gaza, Palestine
    Posts
    25
    this one uses MIME.

    PHP Code:
    <?
        
    //change this to your email.
        
    $to "[email protected]";
        
    $from "[email protected]";
        
    $subject "Hello! This is HTML email";

        
    //begin of HTML message
        
    $message "<html>
      <body bgcolor=\"#DCEEFC\">
        <center>
            <b>Looool!!! I am reciving HTML email......</b> <br>
            <font color=\"red\">Thanks Mohammed!</font> <br>
            <a href=\"http://www.maaking.com/\">* maaking.com</a>
        </center>
          <br><br>*** Now you Can send HTML Email <br> Regards<br>MOhammed Ahmed - Palestine
      </body>
    </html>"
    ;
       
    //end of message

        // To send the HTML mail we need to set the Content-type header.
        
    $headers "MIME-Version: 1.0rn";
        
    $headers .= "Content-type: text/html; charset=iso-8859-1rn";
        
    $headers  .= "From: $from\r\n";
        
    //options to send to cc+bcc
        //$headers .= "Cc: [email][email protected][/email]";
        //$headers .= "Bcc: [email][email protected][/email]";
        
        // now lets send the email.
        
    mail($to$subject$message$headers);

        echo 
    "Message has been sent....!";
    ?>
    the easy can be hard.
    Mohammed Ahmed - ME. Palestine
    http://www.maaking.com
    Email/MSN: [email protected]

  4. #3
    Join Date
    Apr 2002
    Location
    New Jersey
    Posts
    354
    If you are looking for a great php mailer class I would recommend http://phpmailer.sourceforge.net.

    I have been using this class for 3 years and love it. It has tons of features, redundant smtp servers, smtp auth, word wrap, multiple tos, ccs, etc.

    This class is also works really weel with attachments. I use it to send spreadsheet bandwidth reports based on sql queries.

  5. #4
    Join Date
    Jul 2005
    Location
    Minnesota, USA
    Posts
    6
    Originally posted by Aaton35
    If you are looking for a great php mailer class I would recommend http://phpmailer.sourceforge.net.

    I have been using this class for 3 years and love it. It has tons of features, redundant smtp servers, smtp auth, word wrap, multiple tos, ccs, etc.

    This class is also works really weel with attachments. I use it to send spreadsheet bandwidth reports based on sql queries.
    Thanks for that link! I checked it out and it looks like I can definitely find a use for this. Thanks again!

  6. #5
    phpclasses.net is a great resource for all this kind of stuff

    hth

    craig

  7. #6
    Join Date
    Sep 2004
    Location
    England UK
    Posts
    121
    for more information on php's mail() function you can visit: php sendmail tutorial
    Read Tabloids - Warning Experimental.

  8. #7
    take a look at PEAR project functionalities - it has everything, that someone can struggle for....

  9. #8
    Great Mohammed

    but if i need this email send it to me at specific time ??? what is the change
    can i make to do that ?

    thanxs

  10. #9

    Sending PHP in the HTML sent via PHP :)

    Hey thanks for anyhelp offered.

    I am hoping to use this code at the start of this thread to send HTML to users. The email send the HTML but if I do an:

    <? echo "$Vars"; ?> in the code the php does not show up?

    Is there a way to get dynamic data sent in the HTML via PHP?

    thanks so much for your help.

    -Ed

  11. #10
    Join Date
    Nov 2005
    Posts
    268
    yes ed
    In Heredoc or regular strings using $varname or {$varname} will give you the dynamic output you want.

    PHP Code:
    //Any of these methods will allow inserting of variable values into the variable
    $drink "Coke";
    $se "her";
    $heredoc <<< EMAIL
    The Customer would like a straw in $se $drink.
    EMAIL;
    $stringdblquote "The Customer would like a straw in $se $drink.";
    $concatnate 'The Customer would like a straw in ' $se ' ' $drink;
    //unfortunatly without using {} php becomes greedy. 
    $invalid "The Customers would like a straw in their $drinks."//outputs "The Customers would like a straw in their ."
    //using {} can force php to evalueate the correct number of letters.
    $valid "The Customers would like a straw in their {$drink}s."//outputs "The Customers would like a straw in their Cokes." 

  12. #11

    A thousand thanks to Korvan

    hey Thanks so much Korvan for the advice I was looking for. It really helped me out. I am pretty pumped about sending dynamic data in emails in HTML and php.


    thanks!


    HUE THEM ANN!



    -Ed

  13. #12

    One More Question

    Hey Korvan,

    Another question for you. How do I use a for in this html? You will see my example below. Basically I am calling the VARS from a datadase and creating html tables base on the number of results. Then I want to email those VARS in an html format. Any suggestions?

    I tried useing $HTML_Data = 'include'DatabaseScript.php'; and then putting $HTML_VAR in the code below in place of the For Loop, but that didn't work either.

    thanks for your time. If you have a paypal account I would like to donate something to you to say thanks for your time. Have a great night.


    //Any of these methods will allow inserting of variable values into the variable
    $drink = "Coke";
    $se = "her";
    $heredoc <<< EMAIL

    <? $TheCount++; for($i=1; $i < $TheCount; $i++) { $HailMary .=$ItemsOrdered[$i][0];$HailMary .=$ItemsOrdered[$i][1];$HailMary .=$ItemsOrdered[$i][2]; $HailMary .=$ItemsOrdered[$i][3]; $HailMary .=$ItemsOrdered[$i][4]; }//$HailMary .= "<br>"; echo "$HailMary"; ?>

    EMAIL;
    $stringdblquote = "The Customer would like a straw in $se $drink.";

  14. #13

    working... kind of.

    Ok so I got an include to work with spiting out the html, however it is not getting my Vars from the Database? Any Suggestions? Here is the code:

    $MyVars = get_include_contents('MyFile.php');
    function get_include_contents($filename) {
    if (is_file($filename)) {
    import_request_variables ( 'gp' );
    ob_start();
    include $filename;
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
    }
    return false;
    }



    //begin of HTML message
    $message = <<<EOF

    $MyVars
    EOF;

  15. #14
    Join Date
    Nov 2005
    Posts
    268
    I do not know how to fix that unless i know whats query you are running.

    So what is your sql query? I could give you an example

    Also you cannot put <? ... ?> inside the heredoc and expect php to process that code. It just wont, instead it will output those tags. (or dump them in a var).
    PHP Code:
    //you only can run database query after the connection to your database is open.
    $sql "SELECT id, name, job FROM example_tbl";
    if(!(
    $result mysql_query($sql)))
    {
     
    //error
    }
    else
    {
      
    //grab data from the database

      
    $output NULL;
      
    //create our welcome or header message
      
    $output .= "Hello Dude, this is an example email!<br />\r\n";
      while((
    $arr mysql_fetch_assoc($result)))
      {
       
    $output .= "Person <b>{$arr['name']}</b> does {$arr['job']}<br />\r\n";
      }
     
    //close the output
     
    $output .= "<br />\r\n<br />\r\nHave a nice day!<br />\r\n Mr. Ed";

    }
    //output now contains what you are emailing. note this is just an example and 
    //you will need to adjust it to fit your needs. 

  16. #15

    Post 4

    See example below:

  17. #16

    PHP EXAMPLE problem


    Here's what I want to do essentially. Example text - No real code.

    ----------------------------------------------------------------------
    HTML-1 OPENING TAGS - - webmail Page:
    ----------------------------------------------------------------------


    =======================================
    PHP-1 CODE:

    $MY_VAR = <<<EOF // The Var to send in an email.
    =======================================
    +++++++++++++++++++++++++++++++++++++++
    HTML-2 CODE OPENING TAGES TO BE EMAILED - - - - INSIDE OF $MY_VAR
    +++++++++++++++++++++++++++++++++++++++
    ################################
    PHP-2 CODE - inside of HTML CODE INSIDE OF PHP

    -Collects Names from SQL DATABASE and ouputs HTML TABLES with PHP VARS within the HTML HEADERS to be emailed.
    ################################
    +++++++++++++++++++++++++++++++++++++++
    HTML-2 CODE CLOSING TAGS TO BE EMAILED - - STILL INSIDE - - $MY_VAR
    +++++++++++++++++++++++++++++++++++++++

    =======================================
    PHP-2 CODE:
    EOF; // Closes VAR to be emailed.
    EMAIL code to email - $THE_VARS to receipent.
    =======================================

    ----------------------------------------------------------------------
    HTML-2 CLOSING TAGS - - webmail Page:
    ----------------------------------------------------------------------

    Does this make sense? What code can I safely put in the orange and loop through a database to output html tables and PHP vars?

  18. #17
    Join Date
    Nov 2005
    Posts
    268
    You cant do that that way using heredoc. You must terminate heredoc before you can process any php code. You can restart heredoc using $my_var .= <<< EOF
    more text
    EOF;
    but you cant proccess with a for loop in heredoc.

    here is what you should do as far as page format.
    Move the red things all the way down to the bottom, so you really start your webmail page after all the processing is done.

    Second, for the purple part you can use my code as the basic structure for generating the document. It will give you the results you are looking for.

  19. #18
    Join Date
    Nov 2007
    Location
    England
    Posts
    8
    Very very very nice tutorial

    I have done many of theses.

  20. #19
    wow this is exacly what I needed for a mod I'm making for Vbulletin. Thx

  21. #20
    Join Date
    Jan 2005
    Location
    UK, London
    Posts
    762
    why not just use this : http://phpmailer.sourceforge.net/

    Simple and just works

  22. #21
    Quote Originally Posted by Korvan View Post
    I do not know how to fix that unless i know whats query you are running.

    So what is your sql query? I could give you an example

    Also you cannot put <? ... ?> inside the heredoc and expect php to process that code. It just wont, instead it will output those tags. (or dump them in a var).
    PHP Code:
    //you only can run database query after the connection to your database is open.
    $sql "SELECT id, name, job FROM example_tbl";
    if(!(
    $result mysql_query($sql)))
    {
     
    //error
    }
    else
    {
      
    //grab data from the database

      
    $output NULL;
      
    //create our welcome or header message
      
    $output .= "Hello Dude, this is an example email!<br />\r\n";
      while((
    $arr mysql_fetch_assoc($result)))
      {
       
    $output .= "Person <b>{$arr['name']}</b> does {$arr['job']}<br />\r\n";
      }
     
    //close the output
     
    $output .= "<br />\r\n<br />\r\nHave a nice day!<br />\r\n Mr. Ed";

    }
    //output now contains what you are emailing. note this is just an example and 
    //you will need to adjust it to fit your needs. 

    This piece of code saved me from jumping off the nearest bridge. I am extremely grateful for this. Unlike me, you are a genius!

  23. #22
    Join Date
    Sep 2008
    Location
    SE Michigna
    Posts
    3

    use a php include for the html code

    How can insert a .php file instead of the html code?

    In other words.....I'd like to take the html code that an external .php file has (it's only html code) and insert as html into this script?

  24. #23
    So if we have to change back to html to php can we do it, in case we don't want to change in HTML??

  25. #24
    works find thanks

  26. #25
    Join Date
    Apr 2008
    Location
    Montreal, Qc., Canada
    Posts
    306
    For the power users out there, here's the "complicated code to send HTML email"... heheh.

    No worries, I've taken most of this from previous projects and thought I may share a bit of knowledge since this topic has nearly 1M views. Using sockets gives you notably the flexibility to bind your chosen IP and perform "SMTP validation".

    PHP Code:
    <?php

    // Recipient's email address and name (optional)
    $to['address'] = [email protected]';
    $to['name'] = '';

    // Sender's email address and name (optional)
    $from['address'] = [email protected]';
    $from['name'] = 'John Doe';

    // Message's subject
    $subject 'Hey hey!';

    // Message's headers
    $headers[] = 'Date: ' date('r');
    $headers[] = "From: {$from['name']} <{$from['address']}>";
    $headers[] = "To: {$to['name']} <{$to['address']}>";
    $headers[] = "Subject: {$subject}";
    $headers[] = 'Content-Type: text/html; charset=iso-8859-1';

    // Message's body
    $message = <<<HTML

    <b>Hey!</b><br />
    Here is a sample message with some <a href='google.com'>HTML</a> goodness.

    HTML;

    // IP address to send message from, Apache got to run as root
    $IP '127.0.0.1';

    // Make sure recipient's address makes sense
    if (preg_match('/.+@.+/'$to['address']))
    {
        
    // Get the domain
        
    $domain explode('@'$to['address']);
        
        
    // Find domain's MX records
        
    if (getmxrr($domain[1], $mxhosts))
        {
            
    // Will try sending message using all MX records until success
            
    foreach ($mxhosts as $mxhost)
            {
                
    // Create socket resource
                
    $socket socket_create(AF_INETSOCK_STREAMSOL_TCP);
                
    socket_connect($socket$mxhost25);
                
                
    // Set a 15 seconds timeout to socket, plenty of time
                
    socket_set_option($socketSOL_SOCKETSO_RCVTIMEO, array('sec' => 15'usec' => 0));
                
    socket_set_option($socketSOL_SOCKETSO_SNDTIMEO, array('sec' => 15'usec' => 0));
                
                
    // Bind desired IP to socket
                
    @socket_bind($socket$IP25);
                
                if (
    dialog_read($socket))
                {
                    if (
    dialog_write($socket'HELO localhost'))
                    {
                        if (
    dialog_write($socket"MAIL FROM: <{$from['address']}>"))
                        {
                            
    // If you wish to stop the delivery if the host server claims the recipient doesn't exists (this is unreliable), remove "!== null"
                            
    if (dialog_write($socket"RCPT TO: <{$to['address']}>") !== null)
                            {
                                if (
    dialog_write($socket'DATA'))
                                {
                                    if (
    dialog_write($socketimplode("\r\n"$headers) . "\r\n{$message}\r\n.") !== false)
                                    {
                                        echo 
    'Message successfully sent!<br/>';
                                        
    dialog_write($socket'QUIT');
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                
                
    socket_close($socket);
            }
        }
    }

    /**
     * Write message specified as parameter to the socket
     * @param resource $socket
     * @param string $buffer
     * @return boolean
     */
    function dialog_write($socket$buffer)
    {
        if (
    socket_write($socket"{$buffer}\r\n") !== false)
        {
            return 
    dialog_read($socket);
        }
    }

    /**
     * Read host's response and determine if we move on
     * @param resource $socket
     * @return boolean
     */
    function dialog_read($socket)
    {    
        if ((
    $responses socket_read($socket1024)))
        {
            
    $responses explode("\n"$responses);
            
            
    // For each responses
            
    foreach ($responses as $response)
            {
                if (
    $response != '')
                {
                    echo 
    $response '<br/>';
                    
                    
    // For the sake of simplicity, anything but 4XX and 5XX codes will be considered as valid.
                    
    $response substr($response01);
                    
                    switch (
    $response)
                    {
                        case 
    '4':
                            
    // Temporary error, require socket's re-creation
                            
    return null;
                            break;
                        
                        case 
    '5':
                            
    // Invalid recipient, email declined, etc...
                            
    return false;
                            break;
                    }
                }
            }
            
            
    // Anything else is considered as valid, without error
            
    return true;
        }
        
        return 
    false;
    }
    Heymman - Beefy servers, tiny price !

  27. #26
    Join Date
    Jun 2011
    Location
    Ontario, Canada
    Posts
    5
    If you're looking for a simple code, just get any mailing code and add this line to the header:

    $headers[] = 'Content-Type: text/html; charset=iso-8859-1';
    you can replace iso-8859-1 with any character set you want.. I usually use UTF-8

  28. #27
    Quote Originally Posted by latheesan View Post
    why not just use this : http://phpmailer.sourceforge.net/

    Simple and just works
    Yes, PHPMailer does the job. It'll also only cost you 4-5 lines of code. Been always using it - if properly configured, mails never land in Spam.

  29. #28
    I am still learning html too! Thanks for sharing

  30. #29
    Join Date
    Aug 2011
    Posts
    11
    Quote Originally Posted by mafiS View Post
    Yes, PHPMailer does the job. It'll also only cost you 4-5 lines of code. Been always using it - if properly configured, mails never land in Spam.

    Easiest way to go right here... I use phpmailer extensively and it alleviates many stresses, specially when dealing with attachments.

  31. #30
    interesting good job, simple and expandable, i enjoyed the thread.

  32. #31
    Great work!
    Thanks

  33. #32
    ty for all the tuts here and ty for the link i like that email system

  34. #33
    Thanks for the codes.

  35. #34
    The code works very well, thanks for that; beats using a plug-in.

  36. #35
    Join Date
    Sep 2002
    Location
    Top Secret
    Posts
    11,516
    Don't EVER use php's mail() function to send mail. That's just asking to be thrown into the junk pile, and run into issues down the road. Use a proper system. Setup a dedicated mail account, use smtp, authenticate, and make it work correctly.

    Start here, look at the examples (yes, there are html mail examples), get your code working right!
    WHMCS Guru - WHMCS addons, management, support and more.
    WHMCS Notifications Extended - Add slack, hipchat, SMS, pushover to WHMCS !!
    Linux Problems? WHMCS Issues? +1-866-546-8914 (linux-14) or @whmcsguru on twitter!

  37. #36
    Quote Originally Posted by twhiting9275 View Post
    Don't EVER use php's mail() function to send mail. That's just asking to be thrown into the junk pile, and run into issues down the road. Use a proper system. Setup a dedicated mail account, use smtp, authenticate, and make it work correctly.

    Start here, look at the examples (yes, there are html mail examples), get your code working right!
    Seems like a more sophisticated approach to a fairly simple task of sending emails via php on your site. But I think Iíll give it a look in, though Iíve had reasonable success with this method.

  38. #37
    Join Date
    Sep 2002
    Location
    Top Secret
    Posts
    11,516
    Quote Originally Posted by rdokoye View Post
    Seems like a more sophisticated approach to a fairly simple task of sending emails via php on your site. But I think Iíll give it a look in, though Iíve had reasonable success with this method.
    It's really not that sophisticated, and it (pretty much) future proofs your site and gives you the confidence to know it should work with pretty much anything

    more and more hosts are (wisely) disabling php's mail() function, or nobody mail. Why? Because it's a massive spam tool.
    WHMCS Guru - WHMCS addons, management, support and more.
    WHMCS Notifications Extended - Add slack, hipchat, SMS, pushover to WHMCS !!
    Linux Problems? WHMCS Issues? +1-866-546-8914 (linux-14) or @whmcsguru on twitter!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •