Web Hosting Talk







View Full Version : php: simple code to send HTML email


making
06-18-2005, 03:35 PM
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..



<?
//change this to your email.
$to = "m@maaking.com";
$from = "m2@maaking.com";
$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: maa@p-i-s.cXom";
//$headers .= "Bcc: email@maaking.cXom";

// now lets send the email.
mail($to, $subject, $message, $headers);

echo "Message has been sent....!";
?>

making
06-18-2005, 03:50 PM
this one uses MIME.


<?
//change this to your email.
$to = "m@maaking.com";
$from = "m2@maaking.com";
$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: maa@p-i-s.cXom";
//$headers .= "Bcc: email@maaking.cXom";

// now lets send the email.
mail($to, $subject, $message, $headers);

echo "Message has been sent....!";
?>

SolarVPS
06-22-2005, 10:50 PM
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.

mike.fro
07-05-2005, 10:27 PM
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!

craigymcfly
11-23-2005, 02:49 PM
phpclasses.net is a great resource for all this kind of stuff

hth

craig

dotcomguy01
11-23-2005, 08:55 PM
for more information on php's mail() function you can visit: php sendmail tutorial (http://www.chauy.com/2005/11/php-sendmail-tutorial/)

zergus85
11-28-2005, 08:08 AM
take a look at PEAR project functionalities - it has everything, that someone can struggle for....

ak25
11-29-2005, 05:32 AM
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

Mr Ed
01-22-2006, 05:23 PM
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

Korvan
01-23-2006, 12:10 PM
yes ed
In Heredoc or regular strings using $varname or {$varname} will give you the dynamic output you want.


//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."

Mr Ed
01-23-2006, 03:25 PM
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

Mr Ed
01-23-2006, 09:39 PM
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.";

Mr Ed
01-23-2006, 10:08 PM
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;

Korvan
01-24-2006, 04:51 PM
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).

//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.

Mr Ed
01-24-2006, 06:46 PM
See example below:

Mr Ed
01-24-2006, 06:50 PM
:lovewht::lovewht::lovewht::lovewht::lovewht:
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?
:lovewht::lovewht::lovewht::lovewht::lovewht:

Korvan
01-25-2006, 12:47 PM
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.

Padrone
05-19-2008, 11:49 AM
Very very very nice tutorial :)

I have done many of theses.

rjd22
05-30-2008, 10:51 AM
wow this is exacly what I needed for a mod I'm making for Vbulletin. Thx

latheesan
06-09-2008, 09:11 PM
why not just use this : http://phpmailer.sourceforge.net/

Simple and just works

zaba
06-26-2008, 09:22 AM
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).

//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!

fhahnel
05-04-2011, 04:33 PM
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?

net1234
06-28-2011, 07:02 AM
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??

Divine-vps
07-30-2011, 04:22 PM
works find thanks

WootWoot
07-30-2011, 08:14 PM
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

// Recipient's email address and name (optional)
$to['address'] = 'jane@doe.com';
$to['name'] = '';

// Sender's email address and name (optional)
$from['address'] = 'john@doe.com';
$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_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $mxhost, 25);

// Set a 15 seconds timeout to socket, plenty of time
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 15, 'usec' => 0));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 15, 'usec' => 0));

// Bind desired IP to socket
@socket_bind($socket, $IP, 25);

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($socket, implode("\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($socket, 1024)))
{
$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($response, 0, 1);

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;
}

Ibby93
07-31-2011, 02:33 PM
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

mafiS
08-01-2011, 10:48 AM
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.

hairylossen
08-03-2011, 06:35 AM
I am still learning html too! Thanks for sharing

voicebiz4sale
08-17-2011, 12:40 PM
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.

Acidx
08-26-2011, 10:59 PM
interesting good job, simple and expandable, i enjoyed the thread.

idesignguru
11-20-2011, 05:07 PM
Great work!
Thanks :)

NixonHost
11-24-2011, 11:49 PM
ty for all the tuts here and ty for the link i like that email system

memolipascal
11-27-2011, 09:34 PM
Thanks for the codes.