0% found this document useful (0 votes)
89 views

PHP - Sending Email (Text - HTML - Attachments)

php sending email tutorial

Uploaded by

Herlina Novianty
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

PHP - Sending Email (Text - HTML - Attachments)

php sending email tutorial

Uploaded by

Herlina Novianty
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Home ASP PHP SQL HTML JavaScript Search Contact

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

attempts Hello World!!!


This is simple text email message.
How to Encrypt
Passwords in the --PHP-alt-<?php echo $random_hash; ?>
Database Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
How to Create
CAPTCHA Protection <h2>Hello World!</h2>
using PHP and AJAX <p>This is something with <b>HTML</b> formatting.</p>

Passing JavaScript --PHP-alt-<?php echo $random_hash; ?>--


<?
variables to PHP
//copy current buffer contents into $message variable and delete current output buffer
How to Get the Current $message = ob_get_clean();
//send the email
Page URL
$mail_sent = @mail( $to, $subject, $message, $headers );
Export Database //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
Schema as XML
?>
Create Thumbnail
Images using PHP In the preceding example we add one additional header of Content-type:multipart/alternative and boundary
Using Regular string that marks the different areas of the email. Note that the content type of the message itself is sent as
a mail header, while the content types of the individual parts of the message are embedded in the message
Expressions with PHP
itself. This way, mail clients can decide which part of the message they want to display.
Reading the 'clean'
Sending Email with Attachment
text from DOCX and
ODT with PHP The last variation that we will consider is email with attachments. To send an email with attachment we need
PHP: Reading the to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover,
"clean" text from RTF we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have
a look at the example:
Reading the "clean"
text from PDF with PHP <?php
//define the receiver of the email
Debugging PHP with $to = '[email protected]';
Xdebug //define the subject of the email
$subject = 'Test email with attachment';
Creating Word, Excel //create a boundary string. It must be unique
and CSV files with PHP
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
Record locking in Web //define the headers we want passed. Note that they are separated with \r\n
$headers = "From: [email protected]\r\nReply-To: [email protected]";
applications
//add boundary string and mime type specification
jQuery File Upload $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
How to create a dump //encode it with MIME base64,
of MySQL database in //and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
one click //define the body of the message.
Bike - drop in ob_start(); //Turn on output buffering
?>
phpMyAdmin --PHP-mixed-<?php echo $random_hash; ?>
replacement Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

How to be a better PHP --PHP-alt-<?php echo $random_hash; ?>


developer Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
Subscription This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>


Sign up for the free email Content-Type: text/html; charset="iso-8859-1"
newsletter for new tips,
Content-Transfer-Encoding: 7bit
tutorials and more. Enter
your email address below, <h2>Hello World!</h2>
and then click the button. <p>This is something with <b>HTML</b> formatting.</p>

Privacy Policy --PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>


Subscribe Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>


--PHP-mixed-<?php echo $random_hash; ?>--

<?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

How to install and configure PHP 5 on Windows box


PHP: Variables
How to Encrypt Passwords in the Database

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:

Add To: dzone | digg | del.icio.us | stumbleupon

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

# Posted by sopel | 10 Feb 2007 02:43:41

A word about email header injection will be good.

# Posted by Binny V A | 11 Feb 2007 08:33:06

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?

# Posted by Luke | 19 Mar 2007 14:16:56

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

# Posted by Justin Dalrymple | 26 Mar 2007 13:08:36

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.

# Posted by Lennart Weijl | 4 Apr 2007 03:27:05

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?

# Posted by tom | 2 May 2007 17:21:26

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.

Any help would be greatly appreciated.

# Posted by Royden Tan | 16 May 2007 23:23:04

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?

# Posted by Joyce | 17 May 2007 10:22:19

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.

# Posted by Elise | 24 May 2007 01:28:56

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?

Here's the code:

<?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

$headers = "From: $from


Reply-To: $from";
//add boundary string and mime type specification
$headers .= "
Content-Type: multipart/mixed; boundary="PHP-mixed-".$random_hash.""";
//Userfile information
$filename = $_FILES["userfile"]["name"]; // gives you the name of the file they uploaded
$filetype = $_FILES["userfile"]["type"]; // gives you the size of the upload in bytes
$filetemp = $_FILES["userfile"]["tmp_name"]; // gives you the temporary name of the file on the server until it is renamed
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$data = base64_encode($filename);
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>


Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

Address is: <?php echo $_POST["address"]; ?>


Phone Number is: <?php echo $_POST["phone"]; ?>
Birthdate is: <?php echo $_POST["bdate"]; ?>

--PHP-alt-<?php echo $random_hash; ?>


Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

<h1>Address is: <?php echo $_POST["address"]; ?></h1>


<p>Phone Number is: <?php echo $_POST["phone"]; ?><br />
Birthdate is: <?php echo $_POST["bdate"]; ?></p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>


Content-Type: $filetype; name=$filename
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $data; ?>


--PHP-mixed-<?php echo $random_hash; ?>--

<?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";
?>

# Posted by Brandon | 2 Oct 2007 22:02:39

what is the code for sending to multiple email addresses?


example: email updates of the site.

# Posted by Hazel Joanne | 1 Nov 2007 23:02:17

To all those with the HTML code showing up instead of the actual email, try replacing all the
with

Good luck

# Posted by Eli N. | 2 Feb 2008 09:02:39

It's a wonderfull tutorial.It fits what I was looking for.


Es un magnifico tutorial. Se ajusta perfectamente a lo que necesitaba saber. Agraezco mucho su desinteresada forma de publicarlo

# Posted by Carlos | 10 Feb 2008 18:49:28

I am sorry to say, that this script has several problems.

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.

# Posted by Chris | 5 Mar 2008 07:39:38

This is the best of the bunchon <a href="http://www.hotscripts.com/Detailed/67232.html">hotscripts</a>

Thanks
James

# Posted by James | 7 Mar 2008 08:44:19

Thanks for your excellent tutorials.


I have a query.
I am using PHP GD Library to produce an image in an IFRAME. I want to e-mail the produced image either as an attachment or as a
link. How is this possible.

# Posted by jacee | 21 Apr 2008 07:09:12

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.

Being able to send attachments is also terrific!

# Posted by Scott | 25 Apr 2008 12:19:11

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

Plan text message goes here

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

# Posted by Jason Morriss | 28 Apr 2008 09:25:53

Joyce, look up something called a cron job. For the webserver I used I have many cron jobs running all the the time.

# Posted by Mark | 20 May 2008 19:28:06

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.

# Posted by kiwibrit | 24 May 2008 02:26:38

function mail_attachment ($from , $to, $subject, $message, $attachment){


$fileatt = $attachment; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$start= strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment

$email_from = $from; // Who the email is from


$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it

$email_to = $to; // Who the email is to

$headers = "From: ".$email_from."


";
//$headers = "From: ".$email_from;

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

$email_message .= "This is a multi-part message in MIME format.

".
"--{$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}--
";

$ok = mail($email_to, $email_subject, $email_message, $headers);

if($ok)
{
}

else
{
// print "<b>Sorry Could not send</b>";
}
}

# Posted by Andrew Fletcher | 3 Sep 2009 00:00:00

Copyright © 2005-2014
www.WebCheatSheet.com All
Rights Reserved.

You might also like