Sometimes you want to send mail from your php code, maybe you want to send a mail to yourself on an event or send a message to your users or subscribers, don’t fear this is not a hard task to accomplish, and as usual in programming, there is many paths to the same goal, some are not as safe and stable, while others may require a little more effort. It all depends on your needs.


Option 1: PHP’s built-in mail function (Not recommended)

Sending mail with PHP is quite easy if the server is set up for it. The server needs to have SendMail installed and configured correctly in php.ini. There are also some people reporting that mail doesn’t reach the destination, even though the mail was sent without an error message and some providers does not allow mails sent by php mail() to prevent spam.

Also if you want custom headers and attachments or special encodings you have a lot of job in front of you. I had this issue myself  a while ago when a clients script was sending a PDF file as an attachment using the php mail() function. It worked just fine in testing, I was testing with Gmail, but some recipients got the PDF code garbeled inside the body of the mail.

If this is fine with you, and you are only going to send a mail to yourself and want something simple then you can go ahead and try it out:

mail('', 'PHP test mail', 'This is a test mail');

If the mail appear in your inbox, the server is configured correctly and you can use it for simple mails, but bear in mind that this is not stable.

Option 2: Use a dedicated mail class

If you want something more stable than the php mail function you should try a mail class that gives you a lot of functionality and options, and handles the hard work with attachments and headers for you.

There is a open source project called PHPMailer available that handles file attachments, SMTP servers, CCs, BCCs, HTML messages, word wrap, and more. This class gives you the options to send emails via sendmail, PHP mail(), QMail, or using your own SMTP server.

All you need to do is download the class files and include it to your project to get going.

A simple example showing how to send emails using your own SMTP server.

include 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->Host = '';
$mail->SetFrom('', 'Your name');
$mail->AddReplyTo('', 'Your name');
$mail->Subject = 'PHP test mail';
$mail->Body('This is a test mail sent from php'); 

if(!$mail->Send()) {
    echo('Mail not sent: '.$mail->ErrorInfo;
} else {
    echo('Mail sent successfully!');

If this example does not suit your needs, you can find more advanced examples over at the developers website using other choices to send mail, and Gmail SMTP.