PHP - Sending Email (Text - HTML - Attachments)
PHP - Sending Email (Text - HTML - Attachments)
Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The
goal of this tutorial is to demonstrate how to generate and send emails in PHP.
So, you want to send automated email messages from your PHP application. This can be in direct response
to a user's action, such as signing up for your site, or a recurring event at a set time, such as a monthly
newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To
understand how to send each variation that may exist on an email, we will start with the simple example and
move to the more complicated.
Search Sending a Simple Text Email
Sending HTML Email
Sending Email with Attachments
Search
Note that to send email with PHP you need a working email server that you have permission to use: for Unix
or browse popular tags
machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your php.ini file
to point to your email server.
PHP Tutorial Sending a Simple Text Email
What is PHP?
At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending
What can php do for email, which takes three basic and two optional parameters. These parameters are, in order, the email
you? address to send to, the subject of the email, the message to be sent, additional headers you want to include
How to install and
and finally an additional parameter to the Sendmail program. The mail() function returns True if the message
is sent successfully and False otherwise. Have a look at the example:
cofigure PHP 5 on
Windows box <?php
//define the receiver of the email
Your first PHP Script $to = '[email protected]';
Variables
//define the subject of the email
$subject = 'Test email';
Constants //define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
Arrays //define the headers we want passed. Note that they are separated with \r\n
Sorting Arrays $headers = "From: [email protected]\r\nReply-To: [email protected]";
//send the email
Multidimensional $mail_sent = @mail( $to, $subject, $message, $headers );
Arrays
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
Conditional Statements ?>
Looping Statements
As you can see, it very easy to send an email. You can add more receivers by either adding their addresses,
Functions
comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don't receive the test mail,
Form Processing you have probably installed PHP incorrectly, or may not have permission to send emails.
Using Cookies in PHP
Back to top
Dynamic Image
Sending HTML Email
Generation
File Upload The next step is to examine how to send HTML email. However, some mail clients cannot understand HTML
emails. Therefore it is best to send any HTML email using a multipart construction, where one part contains
Sending Email
a plain-text version of the email and the other part is HTML. If your customers have HTML email turned off,
(Text/HTML they will still get a nice email, even if they don't get all of the HTML markup. Have a look at the example:
/Attachments)
<?php
Working with //define the receiver of the email
Directories $to = '[email protected]';
//define the subject of the email
How to connect to $subject = 'Test HTML email';
MySQL database using //create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
PHP $random_hash = md5(date('r', time()));
How to connect to
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: [email protected]\r\nReply-To: [email protected]";
MSSQL database //add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
DSN and DSN-less
//define the body of the message.
connections ob_start(); //Turn on output buffering
?>
Blocking access to the
--PHP-alt-<?php echo $random_hash; ?>
login page after three Content-Type: text/plain; charset="iso-8859-1"
unsuccessful login
Content-Transfer-Encoding: 7bit
Hello World!!!
Subscription This is simple text email message.
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have
multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two
versions of the email. To include an attachment to our message, we read the data from the specified file into
a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME
specifications and then include it as an attachment.
Back to top
Related Articles
For more information about the PHP mail() function, visit PHP Mail Reference.
Worldwide SMTP Service
Sign Up For Free. Only Takes 60 Seconds. Money Back Guarantee!
Tags:
it's worth mentioning there are great mailer libs like Swift Mailer (http://www.swiftmailer.org/) or ezcMail (http://ez.no
/doc/components/view/2006.2/(file)/introduction_Mail.html).
Hey thanks for this great script and write-up! I'm having some issues with the script combining the plain text w/ the HTML version of
the outgoing email (under Sending HTML Email above).
Maybe 1-3 out of 10 outgoing emails send an empty body. The email is being sent, and the subject is always correct, but the entire
body of the email is empty. Is this a known issue? With a known fix? I'm echoing some PHP variables and an occasional function in the
buffer, but it's weird that I'm getting a blank email on an inconsistent basis. Any ideas?
Another thing worth noting is the formatting of the $headers variables should be followed specifically to this example. For instance:
a) You cannot encapsulate any of the $headers variables within a single quote as the string will be taken literally. This means your
breaks (i.e. "
") will not work and the HTML/Text e-mails will not display correctly in many mail clients. I tested this in Thunderbird and found this to
be the case whereas GMail is still able to handle the message properly.
b) Strings inside of the variables should also be formatted properly using double-quotes instead of single quotes. I tested the boundry
line and was able to produce errors in several mail clients and webmail systems (namely Thunderbird, Yahoo Mail, and GMail). For
example, consider the following portion of code from the headers:
boundary="PHP-alt-".$random_hash.""";
You'll notice the delimited double-quotes in this line so that actual double-quotes are sent with the variable and therefore your
message. If you remove the delimiter and the quotes, this message fails in Thunderbird.
The moral of the story is simple: test these to a science before you drop your code into production. Every major mail client out there is
going to closely follow the related RFC's for handling your messages. But, some of them are going to cover up any mistakes in your
code. Test your code with as many mail clients as possible before you put it out in the world!
--
Justin Dalrymple
Whole Hog Software
http://www.wholehogsoftware.com
Your HTML mail won't work until you add MIME-Version: 1.0 in your header.
Without that you really saved my ass, since I didn't know how to do it and needed it for work.
Thanks.
I'm using the test/html script above and it works great but I'm having a problem.....Does anyone know why I can't display variables in
the email content?
I am running fedora 6 with php5.1.6, there is a mention in the tutorial above which says
"These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you
want to include and finally an additional parameter to the Sendmail program.".
But in the line of code which is shown below, i cant seem to find that additional parameter to send to the Sendmail program.
$mail_sent = @mail( $to, $subject, $message, $headers );
Can someone please help me as when i run the send email code it returns a 'Mail Failed' and i guess it has to do with the sendmail
parameter.
I have code that sends email as I want it. Now I need the code that task manager can run at 6:00 AM. E.g. scheduled batch execute.
"iexplorer.exe" code.php does not work as iexplorer is inter active and needs to display. How to I execute php as a secheduled task?
I'm really sorry to be posting questions here instead of comments. but i need help URGENTLY!
i'm feedback form is working perfectly well in my website. the only thing is that, when the form is sent to my inbox, the informations
received are in codes of html instead of the table i'm suppose to be receiving.
please advice on what i'm suppose to do.
I am trying to send an e-mail with an attachment and I am clueless as to what might be the problem! I have the following code, that
works to send the e-mail as well as show that there is an attachment, but the attachment is a blank file and not the one uploaded.
How can I do this?
<?php
//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = Trim(stripslashes($_POST['subject']));;
//define the sender of the email
$from = Trim(stripslashes($_POST['from']));;
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with
Hello World!!!
This is simple text email message.
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
To all those with the HTML code showing up instead of the actual email, try replacing all the
with
Good luck
1. Sending mail is a pretty common need in web applications. This script is very procedural and not very portable. It should at least be
converted to a function if not encapsulated into a class. It should be re-usable and not specific to the application it is used in.
2. It is very insecure. This script is vulnerable to mail header injection and automated submission.
3. It relies on the return value of mail() to assure the user that the mail has been sent. The mail function does not actually send mail.
It does it's best to format your input into a MIME format email and then hands the message off to an MTA (mail transfer agent like
sendmail, exim or postfix).
Once that transfer is complete, there will be no further indication from PHP that anything went wrong. There are plenty of other things
down stream that can happen to a message, especailly if you do not have the right mail headers. The only conditions under which the
mail function will return false, is if there is incomplete input (which should be caught by validation), or a problem with the MTA.
I would strongly recommend a pre-written mail class for sending mail in PHP. If you really want to use your own code, at least look at
the source code for PHPMailer, Swiftmailer, PEAR::mail or Zend mail before trying it.
Especially in terms of security and spam, scripts like this cause a problem. There is enough spam clogging the internet. Creating more
opportunities for spammers to hit scripts and use bandwidth, affects al of us.
Thanks
James
Awesome, many thanks for this info. I currently have auto replies sent from my website but they are in simply text format, and I have
been thinking about expanding to include a "prettier" html version.
Thank you for the tutorial. I was never sure how to include alternative parts and an attachment until now. But I had several hours of
headaches trying to get this to work on my system.
Outlook is my client and no matter what I did the attachment would never show up in the email once sent. But the html/text
alternatives seemed to work.
In the end, I finally realized the 'closing' boundary blocks that used the double dash on the end of the string. Incase anyone else
missed it see the outline below (headers excluded). Look at the HTML and attachment text for details:
--PHP-mixed-1ff9b9e5c851cbf99345eca9877ba3b1
Content-Type: multipart/alternative; boundary="PHP-alt-1ff9b9e5c851cbf99345eca9877ba3b1"
--PHP-alt-1ff9b9e5c851cbf99345eca9877ba3b1
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
--PHP-alt-1ff9b9e5c851cbf99345eca9877ba3b1
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
HTML content goes here. NOTE THE BOUNDARY STRING BELOW! IT HAS 2 TRAILING dashes on it. this marks the end of the
alternative boundary! w/o those 2 little characters Outlook doesn't realize this is the end of all alternative blocks.
--PHP-alt-1ff9b9e5c851cbf99345eca9877ba3b1--
--PHP-mixed-1ff9b9e5c851cbf99345eca9877ba3b1
Content-Type: text/plain; name="test.php"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
... BASE64 encoded text goes here... Again, look at the boundary string below. It has 2 dashes at the end to close out the 'mixed'
boundary.
--PHP-mixed-1ff9b9e5c851cbf99345eca9877ba3b1--
Joyce, look up something called a cron job. For the webserver I used I have many cron jobs running all the the time.
I did a test run of this script to an address with an Outlook 2003 mail handler. The Outlook preference to convert messages to plain
text was NOT checked.
The plain text message was ignored, the HTML message was converted to plain text. Which is not really what is wanted - since HTML
text may assume other HTML effects.
The same Outlook handler accepts HTML messages without problem - though it does need right-click to download images, of course.
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt="";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "Bcc: [email protected]";
$headers .= "
MIME-Version: 1.0
".
"Content-Type: multipart/mixed;
".
" boundary="{$mime_boundary}"";
$email_txt .= $msg_txt;
".
"--{$mime_boundary}
".
"Content-Type:text/html; charset="iso-8859-1"
".
"Content-Transfer-Encoding: 7bit
".
$email_txt . "
";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}
".
"Content-Type: {$fileatt_type};
".
" name="{$fileatt_name}"
".
//"Content-Disposition: attachment;
".
//" filename="{$fileatt_name}"
".
"Content-Transfer-Encoding: base64
".
$data . "
".
"--{$mime_boundary}--
";
if($ok)
{
}
else
{
// print "<b>Sorry Could not send</b>";
}
}
Copyright © 2005-2014
www.WebCheatSheet.com All
Rights Reserved.