Sending Email From PHP
Sending Email From PHP
This tutorial shows how you can easily send email messages from a PHP-enabled web server. It can be utilized for processing forms data, sending alerts, etc. It also explains a bit about email headers formatting.
Obviously you need to have a web server installed together with PHP. You also need to make sure that your operating system has some email agent installed (for example Sendmail on Linux or SMTP service under IIS). And make sure that port 25 is not being blocked. This is required even if you relay messages via second server.
PHP has mail function enabled by default. However you can specify the additional options in 'php.ini' file in [mail function] section (line # around 700).
Here is the full syntax of mail() command:
bool mail ( string $email_address_to, string $subject, string $message_contents [, string $additional_headers [, string $additional_parameters]] );
The first 3 parameters do not require any explanation: recipient email address, subject of the message, contents of the message. $additional_headers parameter includes email headers which I will list later. $additional_parameters is used to pass options specific for the program used for sending email (such as sendmail) and is rarely used. You need to check the man pages of sendmail for the list of options.
The absolute minimum requires you to specify these:
mail ( $email_address_to , $subject, $message_contents );
However it is recomended to define additional headers for the compliance reasons. Email message must be compatible with RFC #822.
Example below shows some email headers which can be used:
Important thing to remember is that header name are case-sensitive and that each header must be ended with return and newline characters.
Each message is routed via minimum 2 email servers (sender and recipient). However there might be more email servers in the route such as relay servers, antiSPAM servers, etc. Each one of them will add its own headers to your message. You also have to keep in mind that your web server might, depending on the settings, swap some header fields such as Return-Path. Note that this field does not affect the reply-to address.
Here is a simple example that will send an email message:
<?php $email_address_to = "email@example.com"; $subject = "Test email subject"; $message_contents = "Hi! This is the content of the test message."; $header = "From: firstname.lastname@example.org\r\n"; $header .= "Reply-To: email@example.com\r\n"; $header .= "Return-Path: firstname.lastname@example.org\r\n"; mail($email_address_to,$subject,$message_contents,$header); ?>
This example shows more organized structure with more options and more headers:
<?php // --- CONFIG PARAMETERS --- // // $email_recipient = "email@example.com"; $email_sender = "Sender Name