PHP Mail sending script

Posted on:
tags: , ,



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("<p>Message successfully sent!</p>");
  } else {
   echo("<p>Message delivery failed...</p>");
  }
 ?>
That's it! Note that you can have PHP validate your email addresses for correctness before sending.

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.

No comments:

Post a Comment

< >