Sending emails in PHP is very easy. You can use PHP mail function for this purpose. Lets write a simple program which will send an email.
$to = ‘firstname.lastname@example.org’; //Email address to which email will be sent.
$subject = ‘Sending emails in PHP’; // Subject of the email
//Email body or message
$message = ‘Hello, This email is sent to you using PHP mail function.
Have you received this email? ‘;
if( mail( $to, $subject, $message) )
echo ‘Mail is sent.’;
echo ‘An error occurred while sending mail.’;
Now lets analyze the above code line by line.
For sending emails in PHP, we use PHP mail function. This function takes a number of arguments and returns true if the mail is sent or returns false, if the mail is not sent. To send an email using PHP mail function, three arguments should be supplied to the PHP mail function, which are email address to which mail will be sent, a subject for the mail and a message for the mail.
At line 3, we have declared a variable $to and assigned our desired email address to which mail will be sent. Similarly subject for the mail is assigned to $subject at line 5 and message is assigned to $message at line 8.
Now the main action is performed at line 12 .
[php] if ( mail ( $to, $subject, $message ) )[/php]
We have supplied $to, $subject and $message to the mail function. Here we have place the mail function in if-else statement to check whether the mail is sent or not. If mail is sent then the message “Mail is sent.” is displayed, and if mail is not sent, then the message “An error occurred while sending the mail.” is displayed.
So you can see above that how easy sending emails in PHP is ? 😉