Proper way to send e-mail from PHP

Depending on your setup, PHP might not be sending properly encoded e-mails if you just use the mail() function. Specifically, headers might not be properly encoded, and this includes the subject, the To, and Reply-To, etc. Just give it a try using some non-ASCII characters and see if it works. If it doesn't, here's a better way:

// At the beginning of each page load, set internal encoding to UTF-8

// ... rest of initialization code

// Headers are an associative array, unlike the original mail() function
function better_mail($email, $subject, $body, Array $headers = array(), $additional_parameter = NULL) {
    // Make sure we set Content-Type and charset
    if ( !isset( $headers['Content-Type'] ) ) {
        $headers['Content-Type'] = 'text/plain; charset=utf-8';

    $headers_str = '';
    foreach( $headers as $key => $val ) {
        $headers_str .= sprintf( "%s: %s\r\n", $key, $val );

    // Use mb_send_mail() function instead of mail() so that headers, including subject are properly encoded
    return mb_send_mail( $email, $subject, $body, $headers_str, $additional_parameters );

better_mail( '', 'Résumé with non-ASCII characters', 'Résumé content.', array( 'From' => '' ) );

For more information see:

This does not scale well

Here is a piece of code I just found:

# new location
# creates new record or seeks empty record marked by group_id = -2
if($CGI_DATA['new'] == 'New Location') {
  # look for empty - abandoned record
  $SQL  = "SELECT * FROM location WHERE group_id = -2";
  $result = mysql_query($SQL);
  if($row = mysql_fetch_array($result)) {
    $CGI_DATA['location_id'] = $row['location_id'];
  } else {
    $SQL  = "INSERT INTO location SET group_id = '-2',location_bname='New Location',location_roomnum='',
    $result = mysql_query($SQL);
    $CGI_DATA['location_id'] = mysql_insert_id();

A little background: this application has a number of groups each of which can specify several locations. What the above code does is it inserts a location with an "invalid" (-2) group_id, and then allows you to "edit" that record on the next page load. I don't know how they thought this was acceptable.

Page 1 / 1