PHP Programming/Mailing

< PHP Programming

The mail function is used to send E-mail Messages through the SMTP server specified in the php.ini Configuration file.

bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])

The returned boolean will show whether the E-mail has been sent successfully or not.

This example will send message "message" with the subject "subject" to email address "example@domain.tld". Also, the receiver will see that the eMail was sent from "Example2 <example2@domain.tld>" and the receiver should reply to "Example3 <example3@domain.tld>"

 mail(
  "example@domain.tld", // E-Mail address
  "subject", // Subject
  "message", // Message
  "From: Example2 <example2@domain.tld>\r\nReply-to: Example3 <example3@domain.tld>"  // Additional Headers
 );

There is no requirement to write E-mail addresses in format "Name <email>", you can just write "email".

This will send the same message as the first example but includes From: and Reply-To: headers in the message. This is required if you want the person you sent the E-mail to be able to reply to you. Also, some E-mail providers will assume mail is spam if certain headers are missing so unless you include the correct headers your mail will end up in the junk mail folder.

Important notes

Error Detection

Especially when sending multiple emails, such as for a newsletter script, error detection is important.

Use this script to send mail while warning for errors:

 $result = @mail($to, $subject, $message, $headers);

 if ($result) {
     echo "Email sent successfully.";
 } else {
     echo "Email was not sent, as an error occurred.";
 }

Sending To Multiple Addresses Using Arrays

In the case below the script has already got a list of emails, we simply use the same procedure for using a loop in PHP with mysql results. The script below will attempt to send an email to every single email address in the array until it runs out.

 while ($row = mysql_fetch_assoc($result)) {
       mail($row['email'], $subject, $message, null, "-f$fromaddr");
 }

Then if we integrate the error checking into the multiple email script we get the following

 $errors = 0
 $sent = 0
 
 while ($row = mysql_fetch_assoc($result)) {
       $result = "";
       $result = @mail($row['email'], $subject, $message, null, "-f$fromaddr");
       if (!$result) {
           $errors = $errors + 1;
       }
       $sent = $sent + 1;
 }
 
 echo "You have sent $sent messages";
 echo "However there were $errors messages";

For More Information

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.