PHP Programming/Mailing

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 " and the receiver should reply to "Example3 " There is no requirement to write E-mail addresses in format "Name ", 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

 * PHP by default does not have any mail sending ability itself. It needs to pass the mail to a local mail transfer agent, such as sendmail. This means you cannot just run PHP by itself and expect it to send mail; you must have a mail transfer agent installed.
 * Make sure you do not have any newline characters in the to or subject, or the mail may not be sent properly.
 * However, the additional headers field -- which should always include the From: header -- may also include other headers. On PHP for Windows, each header should be followed by \r\n but on Unix versions, you should only include \n between header lines. Don't put \n or \r\n after the final additional header line.
 * The to parameter should not be an address in the form of "Name ". The mail command may not parse this properly while talking with the MTA (Particularly under Windows).

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:

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.

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

For More Information

 * PHP Manual: Mail Functions