How To Send Email With PHP
Sending email with PHP is done with the mail() function. I'll show you how.
To use the mail() function, 4 things are required (see the PHP manual page for the mail() function):
-
The address where the email will be sent to.
-
The subject line of the email.
-
The body content of the email.
-
The email from address. (On some PHP installations, this is optional.)
Optionally, additional header lines can be specified. Also optionally, sendmail parameters may be specified.
Sending an Email
To send email, provide the 4 required items of information to function mail().
Save this code as test.php. Change the $ToAddress to your own and upload the file to your server. Type its URL into your browser and it will attempt to send an email.
<?php $ToAddress = "ToName@example.com"; $Subject = "An example email"; $BodyContent = "This is an example.\n\nJust an example."; $FromHeaderLine = "From: FromName@example.com"; $success = mail( $ToAddress, $Subject, $BodyContent, $FromHeaderLine ); if( $success ) { echo "Email sent."; } else { echo "Unable to send email."; } ?>
To send email, change the values in the above example for the email you're sending.
You now know the minimum required to send email with PHP.
There is more to know, of course. Some of which is below. However, the above is sufficient to let you send email with PHP.
Sending HTML Email with PHP
HTML email requires more header lines. To make it easy on us, we'll use an array to hold them. Then, the implode() function in the mail() function parameter list automatically conforms the additional header lines with a return and a line feed character between each.
Here is how it's done.
<?php $ToAddress = "ToName@example.com"; $Subject = "An example HTML email"; $BodyContent = "<html> <body> <h1>HTML Email</h1> <p>This is an example HTML email.</p> </body> </html>"; $HeaderLines = array(); $HeaderLines[] = "From: FromName@example.com"; $HeaderLines[] = "Content-Type: text/html; charset=\"UTF-8\""; $HeaderLines[] = "Mime-Version: 1.0"; $success = mail( $ToAddress, $Subject, $BodyContent, implode("\r\n",$HeaderLines) ); if( $success ) { echo "HTML email sent."; } else { echo "Unable to send HTML email."; } ?>
For HTML email, the header lines tell the email reader the body content shall be presented as HTML. The email body content contains HTML markup, from <html> to </html>
More header lines may be added to the $HeaderLines array. Cc:, Bcc:, and Reply-To: are examples. (See the "Field name index" link at Internet mail message header format for a huge list.)
Sending email with PHP can be relatively simple, as the first example in this article show. Sending HTML email is not that tough, either.
For either method, use the above as templates and change the values to suit.
Going beyond that, emailing attachments or embedding images into email, as examples, will require information beyond the scope of this article.
Will Bontrager