PHP: Send mail the simple way

Posted on the 31st of October 2009

One of the fun things of doing web programming, is when you make something that isn’t just visual appealing – but also gives you responds and integrate with other things. In this post I will give a tiny very simple example on how to send a basic text email using PHP.

To send a mail using PHP you can use less than 10 lines of code. Create a php file containing the following code.


<?php
$recipient = "tutorial@jesperchristiansen.dk";
$subject = "This is sent from the tutorial";
$body = "Hi,\n\nIs the tutorial any helpful?";

if (mail($recipient, $subject, $body))
{
echo("<p>We can't stop smiling! The email was sent successfully! :)</p>");
}
else
{
echo("<p>My eyes are in tears, something wen't wrong :/</p>");
}
?>

The above example is pretty straight forward. Vi declare a couple of variables, which is done so that we don’t clutter the mail() function with massive strings of text. The variables consist of recipient, subject and body. Vi use these as arguments in the mail()-function, which returns true if the mail is sent successfully from the PHP code and false if everything explodes and it goes wrong. That is why I have encapsulated it in an if, to make a check whether it went good or not – and display that information to the user.

Simple :)

posted in Development, PHP

Leave a Reply

CommentLuv Enabled