Wednesday, June 16, 2010

How to Send Email from a PHP Script

All it takes is the right configuration (to send mail using a local or a remote server) and one function:

  • mail().

Send Email from a PHP Script Example

The first argument to this function is the recipient, the second specifies the message's subject and the third one should contain the body. So to send a simple sample message, we could use:

<?php
$to = "recipient@example.com";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
if (mail($to, $subject, $body)) {
echo("

Message successfully sent!

");
} else {
echo("

Message delivery failed...

");
}
?>

That's it!

Use Custom Headers (e.g. "From:") in Mail from a PHP Script

Do you want to set a custom From: address, maybe taken from the form you send, or another custom header line? It is but an additional argument you need.

Protecting Your Script from Spammer Exploit

If you use the mail() function (in combination with a web form in particular), make sure you check it is called from the desired page and protect the form with a CAPTCHA maybe. You can also check for suspicious strings in any arguments (say, "Bcc:" followed by a number of email addresses).

Send Email from a PHP Script with SMTP Authentication

If mail() does not work for you, you have options, too. The mail() function included with stock PHP does not support SMTP authentication, for example. If mail() does not work for you for this or another reason, try the PEAR Mail package, which is much more comprehensive and sending mail almost as easily from your PHP scripts.

1 comment:

  1. Thanks for the nice blog. It was very useful for me. I'm happy I found this blog. Thank you for sharing with us,I too always learn something new from your post.
    MLM Script

    ReplyDelete