Last 5.3 release ever available: PHP 5.3.29 - 5.3 now EOL

mail

(PHP 4, PHP 5)

mailEnvoi de mail

Description

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

Envoie un mail.

Liste de paramètres

to

Le ou les destinataires du mail.

Le formatage de cette chaîne doit correspondre avec la » RFC 2822. Voici quelques exemples :

  • destinataire@example.com
  • destinataire@example.com, autre_destinataire@example.com
  • Destinataire <destinataire@example.com>
  • Destinataire <destinataire@example.com>, Autre destinataire <autre_destinataire@example.com>

subject

Sujet du mail à envoyer.

Attention

Le sujet doit satisfaire à la » RFC 2047.

message

Message à envoyer.

Chaque ligne doit être séparée par un caractère CRLF (\r\n). Les lignes ne doivent pas comporter plus de 70 caractères.

Attention

(Windows uniquement) Lorsque PHP discute directement avec un serveur SMTP, si un point est trouvé en début de ligne, il sera supprimé. Pour éviter ce comportement, remplacez ces occurrences par un double point.

<?php
     $text 
str_replace("\n.""\n.."$text);
?>

additional_headers (optionnel)

Chaîne à insérer à la fin des en-têtes du mail.

Ce paramètre est typiquement utilisé pour ajouter des en-têtes supplémentaires (From, Cc et Bcc). Les en-têtes supplémentaires doivent être séparés par un caractère CRLF (\r\n). Si des données externes sont utilisées pour composer cet en-tête, elles doivent être d'abord nettoyées afin de ne pas injecter des données non désirées dans les en-têtes.

Note:

Lors de l'envoi d'un mail, le mail doit contenir un en-tête From. Il peut être défini par le paramètre additional_headers, ou un par défaut peut être défini dans le php.ini.

Ne pas faire ceci causera un message d'erreur similaire à Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. L'en-tête From, sous Windows, définit également l'en-tête Return-Path.

Note:

Si le message n'est pas reçu, essayez d'utiliser uniquement un caractère LF (\n). Quelques agents de transfert de mail Unix (par exemple » qmail) remplacent le caractère LF par le caractère CRLF automatiquement (ce qui revient à doubler le caractère CR si le caractère CRLF est utilisé). Ceci doit être un dernier recours car cela ne correspond pas à la » RFC 2822.

additional_parameters (optionnel)

Le paramètre additional_parameters peut être utilisé pour passer des drapeaux additionnels comme options à la ligne de commande configurée pour être utilisée pour envoyer les mails en utilisant le paramètre de configuration sendmail_path. Par exemple, ceci peut être utilisé pour définir l'adresse d'expéditeur de l'enveloppe lors de l'utilisation de sendmail avec l'option -f.

Ce paramètre est échappé par la fonction escapeshellcmd() en interne afin de prévenir l'exécution d'une commande. La fonction escapeshellcmd() empêche l'exécution d'une commande, mais autorise l'ajout de paramètres supplémentaires. Pour des raisons de sécurité, il est recommandé pour l'utilisateur de nettoyer ce paramètre afin d'éviter l'ajout de paramètres non désirés à la commande shell.

Depuis que la fonction escapeshellcmd() est appliquée automatiquement, quelques caractères autorisés dans les adresses emails par les RFCs d'internet ne peuvent plus être utilisés. La fonction mail() ne peut autoriser ces caractères, aussi, dans les programme où leur utilisation est nécessaire, vous devriez utiliser une méthode alternative pour l'envoi des emails (comme l'utilisation d'un framework ou d'une librairie.

L'utilisateur sous lequel tourne le serveur web doit être ajouté en tant qu'utilisateur de confiance dans la configuration de sendmail afin que l'en-tête X-Warning ne soit pas ajouté au message lorsque l'expéditeur de l'enveloppe (-f) est défini en utilisant cette méthode. Pour les utilisateurs de sendmail, ce fichier est /etc/mail/trusted-users.

Valeurs de retour

Retourne TRUE si le mail a été accepté pour livraison, FALSE sinon.

Il est important de noter que ce n'est pas parce que le mail a été accepté pour livraison qu'il arrivera à destination.

Historique

Version Description
4.3.0 (Windows uniquement) Tous les en-têtes personnalisés (comme "From", "Cc", "Bcc" et "Date") sont supportés et ne sont pas sensibles à la casse. (Parce que les en-têtes personnalisés ne sont pas interprétés par le MTA dans un premier temps mais analysés par PHP, PHP 4.3 supporte uniquement l'en-tête Cc et est sensible à la casse).
4.2.3 Le paramètre additional_parameters est désactivé dans le safe_mode et la fonction mail() affichera un message d'alerte et retournera FALSE lors de son utilisation.
4.0.5 Le paramètre additional_parameters a été ajouté.

Exemples

Exemple #1 Envoi d'un mail

Utilisation de la fonction mail() pour envoyer un mail simple :

<?php
// Le message
$message "Line 1\r\nLine 2\r\nLine 3";

// Dans le cas où nos lignes comportent plus de 70 caractères, nous les coupons en utilisant wordwrap()
$message wordwrap($message70"\r\n");

// Envoi du mail
mail('caffeinated@example.com''Mon Sujet'$message);
?>

Exemple #2 Envoi d'un mail avec des en-têtes supplémentaires

L'ajout d'en-têtes simples, spécifiant au MUA les adresses "From" et "Reply-To" :

<?php
     $to      
'personne@example.com';
     
$subject 'le sujet';
     
$message 'Bonjour !';
     
$headers 'From: webmaster@example.com' "\r\n" .
     
'Reply-To: webmaster@example.com' "\r\n" .
     
'X-Mailer: PHP/' phpversion();

     
mail($to$subject$message$headers);
 
?>

Exemple #3 Envoi d'un mail avec un paramètre de ligne de commande additionnel

Le paramètre additional_parameters peut être utilisé pour passer un paramètre additionnel au programme configuré à être utilisé pour envoyer les mails en utilisant sendmail_path.

<?php
     mail
('personne@example.com''le sujet''le message'null,
     
'-fwebmaster@example.com');
?>

Exemple #4 Envoi de mail HTML

Il est également possible d'envoyer des mails HTML avec la fonction mail().

<?php
     
// Plusieurs destinataires
     
$to  'aidan@example.com' ', '// notez la virgule
     
$to .= 'wez@example.com';

     
// Sujet
     
$subject 'Calendrier des anniversaires pour Août';

     
// message
     
$message '
     <html>
      <head>
       <title>Calendrier des anniversaires pour Août</title>
      </head>
      <body>
       <p>Voici les anniversaires à venir au mois d\'Août !</p>
       <table>
        <tr>
         <th>Personne</th><th>Jour</th><th>Mois</th><th>Année</th>
        </tr>
        <tr>
         <td>Josiane</td><td>3</td><td>Août</td><td>1970</td>
        </tr>
        <tr>
         <td>Emma</td><td>26</td><td>Août</td><td>1973</td>
        </tr>
       </table>
      </body>
     </html>
     '
;

     
// Pour envoyer un mail HTML, l'en-tête Content-type doit être défini
     
$headers  'MIME-Version: 1.0' "\r\n";
     
$headers .= 'Content-type: text/html; charset=iso-8859-1' "\r\n";

     
// En-têtes additionnels
     
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' "\r\n";
     
$headers .= 'From: Anniversaire <anniversaire@example.com>' "\r\n";
     
$headers .= 'Cc: anniversaire_archive@example.com' "\r\n";
     
$headers .= 'Bcc: anniversaire_verif@example.com' "\r\n";

     
// Envoi
     
mail($to$subject$message$headers);
?>

Note:

Si vous prévoyez d'envoyer des mails HTML ou autrement plus complexes, il est recommandé d'utiliser le paquet PEAR » PEAR::Mail_Mime.

Notes

Note:

L'implémentation de la fonction mail() sous Windows diffère de manière significative avec l'implémentation Unix. Tout d'abord, il n'utilise pas un programme local pour composer les messages, mais opère uniquement et directement sur les sockets, ce qui signifie qu'un MTA est nécessairement à l'écoute sur un socket du réseau (qui peut être soit sur le réseau local ou sur une machine distante).

Deuxièmement, les en-têtes personnalisés comme From:, Cc:, Bcc: et Date: ne sont pas interprétés par le MTA dans un premier temps, mais sont analysés par PHP.

De plus, le paramètre to ne doit pas être une adresse sous la forme "Quelque chose <quelqu_un@example.com>". La commande mail n'analysera pas correctement ceci lors de la discussion avec le MTA.

Note:

Il est important de noter que la fonction mail() n'est pas conseillée pour traiter de gros volumes de mails dans une boucle. Cette fonction ouvre et ferme un socket SMTP pour chaque mail, ce qui n'est pas très efficace.

Pour envoyer de gros volumes de mails, reportez-vous aux paquets » PEAR::Mail et » PEAR::Mail_Queue.

Note:

Les RFC suivantes peuvent être utiles : » RFC 1896, » RFC 2045, » RFC 2046, » RFC 2047, » RFC 2048, » RFC 2049 et » RFC 2822.

Voir aussi

add a note add a note

User Contributed Notes 88 notes

up
76
bimal at sanjaal dot com
2 years ago
You can write clean PHP code while creating the headers correctly. First, build a list of all headers in an array. Then, glue them with "\r\n" character.

The code now looks clean and straight forward.
(Just compare it with the manual's example ;-) )

<?php
$headers  
= array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: Sender Name <sender@domain.com>";
$headers[] = "Bcc: JJ Chong <bcc@domain2.com>";
$headers[] = "Reply-To: Recipient Name <receiver@domain3.com>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $email, implode("\r\n", $headers));
?>
up
15
yarik dot bohatsky at gmail dot com
2 years ago
If you want to send UTF-8 HTML letter you need to mention charset twice:

1) In message header:
<?php
$headers
.= 'Content-type: text/html; charset=utf-8' . "\r\n";
?>

2) In HTML header:
<?php
$message
= '
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Fillon soutient à fond le retour d\'un Grand Prix de France</title>
</head>
<body>
   <p>Le Premier ministre François Fillon, passionné d\'automobile et pilote à ses heures, a apporté un soutien appuyé au retour d\'un Grand Prix de France au calendrier 2013 de la Formule 1, en faisant un passage-éclair vendredi sur le circuit Paul Ricard dans le Var.</p>
</body>
</html>
'
;

In this case Outlook will also "understand" that message is encoded using UTF-8.
up
8
php dot net at schrecktech dot com
9 years ago
When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...
up
6
Porjo
4 years ago
Make sure you enclose \r\n in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code
up
6
pavel.lint at vk.com
2 years ago
Here's a small handy function I use to send email in UTF-8.

<?php
function mail_utf8($to, $from_user, $from_email,
                                            
$subject = '(No subject)', $message = '')
   {
     
$from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
     
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";

     
$headers = "From: $from_user <$from_email>\r\n".
              
"MIME-Version: 1.0" . "\r\n" .
              
"Content-type: text/html; charset=UTF-8" . "\r\n";

     return
mail($to, $subject, $message, $headers);
   }
?>
up
4
antoine dot php dot net at bonnefoy dot eu
11 months ago
Hello,

it's sometime hard to include multiple attachment, or to include pictures inside body.

Please find these 2 functions allowing sending email with attachment.
usage :
<?php
echo date("H:i:s");
echo
mail::sendMail("to@domain.com", "Test Attach "date("H:i:s"), "Contenu du mail <a href=3D'domain.com'>domain.com</a>", __FILE__, "xx@domain.com",'' , true);
?>

source :

<?php

class mail {

    public static function
prepareAttachment($path) {
       
$rn = "\r\n";

        if (
file_exists($path)) {
           
$finfo = finfo_open(FILEINFO_MIME_TYPE);
           
$ftype = finfo_file($finfo, $path);
           
$file = fopen($path, "r");
           
$attachment = fread($file, filesize($path));
           
$attachment = chunk_split(base64_encode($attachment));
           
fclose($file);

           
$msg = 'Content-Type: \'' . $ftype . '\'; name="' . basename($path) . '"' . $rn;
           
$msg .= "Content-Transfer-Encoding: base64" . $rn;
           
$msg .= 'Content-ID: <' . basename($path) . '>' . $rn;
//            $msg .= 'X-Attachment-Id: ebf7a33f5a2ffca7_0.1' . $rn;
           
$msg .= $rn . $attachment . $rn . $rn;
            return
$msg;
        } else {
            return
false;
        }
    }

    public static function
sendMail($to, $subject, $content, $path = '', $cc = '', $bcc = '', $_headers = false) {

       
$rn = "\r\n";
       
$boundary = md5(rand());
       
$boundary_content = md5(rand());

// Headers
       
$headers = 'From: Mail System PHP <no-reply@domain.com>' . $rn;
       
$headers .= 'Mime-Version: 1.0' . $rn;
       
$headers .= 'Content-Type: multipart/related;boundary=' . $boundary . $rn;

       
//adresses cc and ci
       
if ($cc != '') {
           
$headers .= 'Cc: ' . $cc . $rn;
        }
        if (
$bcc != '') {
           
$headers .= 'Bcc: ' . $cc . $rn;
        }
       
$headers .= $rn;

// Message Body
       
$msg = $rn . '--' . $boundary . $rn;
       
$msg.= "Content-Type: multipart/alternative;" . $rn;
       
$msg.= " boundary=\"$boundary_content\"" . $rn;

//Body Mode text
       
$msg.= $rn . "--" . $boundary_content . $rn;
       
$msg .= 'Content-Type: text/plain; charset=ISO-8859-1' . $rn;
       
$msg .= strip_tags($content) . $rn;

//Body Mode Html       
       
$msg.= $rn . "--" . $boundary_content . $rn;
       
$msg .= 'Content-Type: text/html; charset=ISO-8859-1' . $rn;
       
$msg .= 'Content-Transfer-Encoding: quoted-printable' . $rn;
        if (
$_headers) {
           
$msg .= $rn . '<img src=3D"cid:template-H.PNG" />' . $rn;
        }
       
//equal sign are email special characters. =3D is the = sign
       
$msg .= $rn . '<div>' . nl2br(str_replace("=", "=3D", $content)) . '</div>' . $rn;
        if (
$_headers) {
           
$msg .= $rn . '<img src=3D"cid:template-F.PNG" />' . $rn;
        }
       
$msg .= $rn . '--' . $boundary_content . '--' . $rn;

//if attachement
       
if ($path != '' && file_exists($path)) {
           
$conAttached = self::prepareAttachment($path);
            if (
$conAttached !== false) {
               
$msg .= $rn . '--' . $boundary . $rn;
               
$msg .= $conAttached;
            }
        }
       
//other attachement : here used on HTML body for picture headers/footers
       
if ($_headers) {
           
$imgHead = dirname(__FILE__) . '/../../../../modules/notification/ressources/img/template-H.PNG';
           
$conAttached = self::prepareAttachment($imgHead);
            if (
$conAttached !== false) {
               
$msg .= $rn . '--' . $boundary . $rn;
               
$msg .= $conAttached;
            }
           
$imgFoot = dirname(__FILE__) . '/../../../../modules/notification/ressources/img/template-F.PNG';
           
$conAttached = self::prepareAttachment($imgFoot);
            if (
$conAttached !== false) {
               
$msg .= $rn . '--' . $boundary . $rn;
               
$msg .= $conAttached;
            }
        }

// Fin
       
$msg .= $rn . '--' . $boundary . '--' . $rn;

// Function mail()
       
mail($to, $subject, $msg, $headers);
    }

}

?>
up
2
Edward
5 years ago
Currently my hosting service is on Godaddy. When attempting to use the mail function without the fifth parameter containing "-f", my message headers would not work.

Whenever your message headers do not work, simply try using the fifth parameter:

<?php
mail
($to, $subject, $message, $headers, "-femail.address@example.com");
?>
up
1
John
4 years ago
A quick note about the optional flags that can be passed to sendmail. -f will set the From address, -r will override the default Return-path that sendmail generates (typically the From address gets used). If you want your bouncebacks to go to a different address than the from address, try using both flags at once: "-f myfromemail@example.com -r mybounceemail@example.com"
up
1
msheldon at desertraven dot com
9 years ago
Just a comment on some of the examples, and as a note for those who may be unaware. The SMTP RFC 822 is VERY explicit in stating that \r\n is the ONLY acceptable line break format in the headers, though is a little vague about the message body. While many MTAs will deal with just \n, I've run accross plenty of them that will exhibit "interesting" behaviours when this happens. Those MTAs that are strict in compliance will definitely break when header lines are terminated with only \n. They will also most likely break if the body of the message contains more than 1000 consecutive characters without a \r\n.*

Note that RFC 821 is a little more clear in defining:
"line
      A a sequence of ASCII characters ending with a <CRLF>."

RFC 821 makes no distinction between header lines and message body lines, since both are actually transmitted during the DATA phase.

Bottom line, best practice is to be sure to convert any bare \n characters in the message to \r\n.

* "The maximum total length of a text line including the <CRLF> is 1000 characters" (RFC 821)
up
2
g dot kuizinas at anuary dot com
1 year ago
<?php
**
* Function
responsible for sending unicode emails.
*
* @
author Gajus Kuizinas <g.kuizinas@anuary.com>
* @
version 1.0.1 (2012 01 11)
*/
function
mail_send($arr)
{
    if (!isset(
$arr['to_email'], $arr['from_email'], $arr['subject'], $arr['message'])) {
        throw new
HelperException('mail(); not all parameters provided.');
    }
   
   
$to            = empty($arr['to_name']) ? $arr['to_email'] : '"' . mb_encode_mimeheader($arr['to_name']) . '" <' . $arr['to_email'] . '>';
   
$from        = empty($arr['from_name']) ? $arr['from_email'] : '"' . mb_encode_mimeheader($arr['from_name']) . '" <' . $arr['from_email'] . '>';
   
   
$headers    = array
    (
       
'MIME-Version: 1.0',
       
'Content-Type: text/html; charset="UTF-8";',
       
'Content-Transfer-Encoding: 7bit',
       
'Date: ' . date('r', $_SERVER['REQUEST_TIME']),
       
'Message-ID: <' . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>',
       
'From: ' . $from,
       
'Reply-To: ' . $from,
       
'Return-Path: ' . $from,
       
'X-Mailer: PHP v' . phpversion(),
       
'X-Originating-IP: ' . $_SERVER['SERVER_ADDR'],
    );
   
   
mail($to, '=?UTF-8?B?' . base64_encode($arr['subject']) . '?=', $arr['message'], implode("\n", $headers));
}
?>

Here is my helper function for those who are having problems properly handling UTF-8, subject, HTML, or even the headers data. I've been using it for over a year. It works fine with simple emails.

For anything more advanced (specifically, handling attachments and multiple email versions), you should be using an existing library like http://swiftmailer.org/.
up
1
shenyqwilliam
1 year ago
If you're sending a large attachment, you may encounter overflow problem.
AFAIK, two common limits could be responsible.

1. Postfix message size limit.
Edit /etc/postfix/main.cf . Change the value of "message_size_limit".

2. Apache memory size limit for scripts.
Edit /etc/php.ini . Change the value of "memory_limit".

//Then reload (or restart) Postfix and Apache.
//Empirically, sending 200MB attachment requires 500MB memory.

Be careful! Raising memory limits may cause unexpected consequences, and is hence deprecated.
Recommended alternatives include:
* Pack and split attachment into several emails.
* Only include a link to the file. The receiver can download it later.
* Use IMAP/POP3 server (e.g. Dovecot).
up
0
pierreantoine dot covet at gmail dot com
5 months ago
Hi,

I had lots of problems using the code in the exemple. HTML was not rightly formated in my email.
Problem solved by replacing "\r\n" by "\n" as header end line.
up
0
rexlorenzo at gmail dot com
2 years ago
Be careful to not put extra spaces for the $headers variable.

For example, this didn't work on our servers:

$headers = "From: $from \r\n Bcc: $bcc \r\n";

But this did:

$headers = "From: $from\r\nBcc: $bcc\r\n";

Notice the removal of the spaces around the first \r\n.
up
0
arunm
2 years ago
It is also advisable to set the return path in the headers; hence it will avoid the email to land in the spam folder!
eg:

$headers.="Return-Path:<name@example.com>\r\n";
up
0
Anda
2 years ago
Send Multi attachment email

<?php
function multi_attach_mail($to, $files, $sendermail){
   
// email fields: to, from, subject, and so on
   
$from = "Files attach <".$sendermail.">";
   
$subject = date("d.M H:i")." F=".count($files);
   
$message = date("Y.m.d H:i:s")."\n".count($files)." attachments";
   
$headers = "From: $from";

   
// boundary
   
$semi_rand = md5(time());
   
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

   
// headers for attachment
   
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

   
// multipart boundary
   
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
   
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

   
// preparing attachments
   
for($i=0;$i<count($files);$i++){
        if(
is_file($files[$i])){
           
$message .= "--{$mime_boundary}\n";
           
$fp =    @fopen($files[$i],"rb");
       
$data =    @fread($fp,filesize($files[$i]));
                    @
fclose($fp);
           
$data = chunk_split(base64_encode($data));
           
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
           
"Content-Description: ".basename($files[$i])."\n" .
           
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
           
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            }
        }
   
$message .= "--{$mime_boundary}--";
   
$returnpath = "-f" . $sendermail;
   
$ok = @mail($to, $subject, $message, $headers, $returnpath);
    if(
$ok){ return $i; } else { return 0; }
    }
?>
up
0
vigo dot von dot harrach at gmx dot de
3 years ago
If using sendmail as transport agent, setting the "DeliveryMode" to "background" (asynchronous) instead of the default "interactive" (synchronous) makes mail() a lot faster, while still sending immediately.
You can either use the "additional parameters", e.g. mail($to, $subject, $message, $headers, 'O DeliveryMode=b'), or make this mode default by changing php.ini's "sendmail_path" to 'sendmail -t -i -O DeliveryMode=b'.
up
0
shuitest at gmail dot com
3 years ago
If you use mutt, do as below,

/usr/bin/mutt -s '$subject' -f /dev/null -e 'set copy=no' -e 'set from = "{$GLOBALS[cfg][email_from]}"' -a '$attach_file_full_path' '{$GLOBALS[cfg][email_to]}' </dev/null 2>&1;
up
0
Erich at gasboysnospam dot net
5 years ago
if your mail is failing (returns false) be aware that many servers are configured to kill mail going out with a bcc or cc header.

The ideal workaround is to use the smtp functions which servers allow because of its better audit trail. Alternatively call the mail function several times.

I've just spent about four hours trying to work out what I was doing wrong!!
up
0
molotster on google mail com
5 years ago
Note, that single line should not contain more than 78 character, but is not allowed to contain more than 998 characters.

The possible consequences are:
Over 78 - clients are allowed to display the message in a "harder to read" way.
Over 998 - clients and servers are allowed to drop the message or cause any buffer-limit error.

See:
http://www.faqs.org/rfcs/rfc2822 part 2.1.1.
up
0
akam
6 years ago
There differenece in body, headers of email (with attachment, without attachment), see this complete example below:
work great for me (LINUX , WIN) and (Yahoo Mail, Hotmail, Gmail, ...)
<?php
$to     
= $_POST['to'];
$email   = $_POST['email'];
$name    = $_POST['name'];
$subject = $_POST['subject'];
$comment = $_POST['message'];

$To          = strip_tags($to);
$TextMessage =strip_tags(nl2br($comment),"<br>");
$HTMLMessage =nl2br($comment);
$FromName    =strip_tags($name);
$FromEmail   =strip_tags($email);
$Subject     =strip_tags($subject);

$boundary1   =rand(0,9)."-"
.rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$boundary2   =rand(0,9)."-".rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);


for(
$i=0; $i < count($_FILES['youfile']['name']); $i++){
if(
is_uploaded_file($_FILES['fileatt']['tmp_name'][$i]) &&
   !empty(
$_FILES['fileatt']['size'][$i]) &&
   !empty(
$_FILES['fileatt']['name'][$i])){
    
$attach      ='yes';
$end         ='';

  
$handle      =fopen($_FILES['fileatt']['tmp_name'][$i], 'rb');
  
$f_contents  =fread($handle, $_FILES['fileatt']['size'][$i]);
  
$attachment[]=chunk_split(base64_encode($f_contents));
  
fclose($handle);

$ftype[]       =$_FILES['fileatt']['type'][$i];
$fname[]       =$_FILES['fileatt']['name'][$i];
}
}

/***************************************************************
Creating Email: Headers, BODY
1- HTML Email WIthout Attachment!! <<-------- H T M L ---------
***************************************************************/
#---->Headers Part
$Headers     =<<<AKAM
From: $FromName <$FromEmail>
Reply-To:
$FromEmail
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="
$boundary1"
AKAM;

#---->BODY Part
$Body        =<<<AKAM
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="
$boundary1"

This is a multi-part message in MIME format.

--
$boundary1
Content-Type: text/plain;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$TextMessage
--
$boundary1
Content-Type: text/html;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$HTMLMessage

--
$boundary1--
AKAM;

/***************************************************************
2- HTML Email WIth Multiple Attachment <<----- Attachment ------
***************************************************************/

if($attach=='yes') {

$attachments='';
$Headers     =<<<AKAM
From: $FromName <$FromEmail>
Reply-To:
$FromEmail
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="
$boundary1"
AKAM;

for(
$j=0;$j<count($ftype); $j++){
$attachments.=<<<ATTA
--$boundary1
Content-Type:
$ftype[$j];
    name="
$fname[$i]"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
    filename="
$fname[$j]"

$attachment[$j]

ATTA;
}

$Body        =<<<AKAM
This is a multi-part message in MIME format.

--
$boundary1
Content-Type: multipart/alternative;
    boundary="
$boundary2"

--
$boundary2
Content-Type: text/plain;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$TextMessage
--
$boundary2
Content-Type: text/html;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$HTMLMessage

--
$boundary2--

$attachments
--
$boundary1--
AKAM;
}

/***************************************************************
Sending Email
***************************************************************/
$ok=mail($To, $Subject, $Body, $Headers);
echo
$ok?"<h1> Mail Sent</h1>":"<h1> Mail not SEND</h1>";
?>
up
0
richard at richard-sumilang dot com
6 years ago
If you are using the sendmail app from an exim package or something you don't really need to change the normal parameters PHP gives it (-t -i) as other posts described.

I just added "-f myemail@example.com" and it worked.

One thing that got me stuck for a few hours was trying to figure out why the return-path was set as the user (user running php) and not what I was setting it with the -f option then I later found at that in order to forcefully set the return-path the user account running the command must be in exim's trusted users configuration! It helps to add trusted_groups as well then everything works fine :)
- Richard Sumilang
up
0
thomas at p-devion dot de
7 years ago
Change the function addattachment for multipartmail to auto detect the mime_content_type ...

<?php
    
function addattachment($file){
        
$fname = substr(strrchr($file, "/"), 1);
        
$data = file_get_contents($file);
        
$i = count($this->parts);
        
$content_id = "part$i." . sprintf("%09d", crc32($fname)) . strrchr($this->to_address, "@");
        
$this->parts[$i] = "Content-Type: ".mime_content_type($file)."; name=\"$fname\"\r\n" .
                          
"Content-Transfer-Encoding: base64\r\n" .
                          
"Content-ID: <$content_id>\r\n" .
                          
"Content-Disposition: inline;\n" .
                          
" filename=\"$fname\"\r\n" .
                          
"\n" .
                          
chunk_split( base64_encode($data), 68, "\n");
         return
$content_id;
     }
?>
up
0
panoramical at gmail dot com
8 years ago
Searched for ages on the internet trying to find something that parses EML files and then sends them...for all of you who want to send an EML files you first have to upload it, read it, then delete it. Here's my function...it's specialised for a single form where the user uploads the EML file.

<?php

if(isset($_POST['submit']))
{

// Reads in a file (eml) a user has inputted
function eml_read_in()
{

   
$file_ext = stristr($_FILES['upload']['name'], '.');
   
   
// If it is an eml file
   
if($file_ext == '.eml')
    {
   
       
// Define vars
       
$dir = 'eml/';
       
$file = $dir.basename($_FILES['upload']['name']);
       
$carry = 'yes';
       
       
// Try and upload the file
       
if(move_uploaded_file($_FILES['upload']['tmp_name'], $file))
        {
       
           
// Now attempt to read the file
           
if($eml_file = file($file))
            {
           
               
// Create the array to store preliminary headers
               
$headers = array();
               
$body = '';
               
$ii = -1;

               
               
// For every line, carry out this loop
               
foreach($eml_file as $key => $value)
                {
               
                   
$pattern = '^<html>';
                   
                    if(((
eregi($pattern, $value)))||($carry == 'no'))
                    {
                   
                       
// Stop putting data into the $headers array
                       
$carry = 'no';
                       
$i++;
                       
$body .= $value;
                       
                    }
                   
                    else
                    {   
                       
                       
// Separate each one with a colon
                       
if(($eml_file_expl = explode(':', $value))&&($carry == 'yes'))
                        {

                       
                           
// The row has been split in half at least...
                           
if(isset($eml_file_expl[1]))
                            {
       
                               
// Put it into the preliminary headers
                               
$headers[$eml_file_expl[0]] = $eml_file_expl[1];
                           
                               
// There might be more semicolons in it...
                               
for($i=2;$i<=$count;$i++)
                                {
                           
                                   
// Add the other values to the header
                                   
$headers[$eml_file_expl[0]] .= ':'.$eml_file_expl[$i];
                                   
                                }
                           
                            }   
                           
                        }       
                   
                    }
                   
                }
               
               
// Clear up the headers array
               
$eml_values = array();
               
$eml_values[to] = $headers[To];
               
$eml_values[from] = $headers[From];
               
$eml_values[subject] = $headers[Subject];
               
$eml_values['reply-to'] = $headers['Reply-To'];
               
$eml_values['content-type'] = $headers['Content-Type'];
               
$eml_values[body] = $body;
               
               
unlink($file);
       
                return
$eml_values;
               
               
                       
            }
           
        }
       
        else
        {
       
            return
'<p>File not uploaded - there was an error</p>';
                       
        }
       
    }
   
}   

// Takes information automatically from the $_FILES array...
$eml_pattern = eml_read_in()

// Headers definable...through eml_read_in() again, but I'm guessing they'll be the same for each doc...

if(mail($eml_pattern[to], $eml_pattern[subject], $eml_pattern[content], $headers)) echo 'Mail Sent';

?>
up
0
Anonymous
8 years ago
correction for class multipartmail

<?php
function addmessage($msg = "", $ctype = "text/plain"){
        
$this->parts[0] ....
?>

if you are adding attachment first and then addmessage you can easy overwrite added attachment - better use

<?php

function addmessage($msg = "", $ctype = "text/plain"){
        
$this->parts[count($this->parts)] ....

?>
up
0
roberto dot silva at mexicoshipping dot net
10 years ago
If you can't use or don't understand how to use the sendmail program from linux, you can use a PEAR object to send mail.

<?php
include("Mail.php");

$recipients = "mailto@example.com";

$headers["From"]    = "mailfrom@example.com";
$headers["To"]      = "mailto@example.com";
$headers["Subject"] = "Test message";

$body = "TEST MESSAGE!!!";

$params["host"] = "example.com";
$params["port"] = "25";
$params["auth"] = true;
$params["username"] = "user";
$params["password"] = "password";

// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory("smtp", $params);

$mail_object->send($recipients, $headers, $body);
?>

In my case, i use a smtp server that require authentication, and sendmail configuration is almost cryptic to me.

PEAR is already installed in PHP 4.0.3 , if not, you must go to http://pear.php.net/ and install it, in my case, I needed to add the Socket.php to the PEAR library.
up
-1
umangberi at gmail dot com
4 years ago
Outlook 2007 seemed to be a little finicky with me to have carriage returns in the headers. So any \r\n resulted in messages that had default apache messages sent over to me.

As soon as I removed \r from all of the headers, the script started working fine. Hope that helped.
up
-1
martin dot farrow at versacloud dot com
2 years ago
I've noticed that on some versions of PHP occasionally mail() returns the empty string for success, rather than true or false. The empty string evaluates to false.

if you use constructs like

if ( mail( ... ) ){
  # do something here on success
}

this wont work consistently.

so you need code like

$ret=mail(....)

if ( $ret == '' || $ret ){
  # do something here
}

to get consistent results.
up
-1
ABOMB
2 years ago
I was having delivery issues from this function to Gmail, Yahoo, AOL, etc.  I used the notes here to figure that you need to be setting your Return-Path to a valid email to catch bounces.  There are two extra delivery gotchas on top of that:

1) The domain in the email used in the -f option in the php.ini sendmail parameter or in the mail() extra parameters field, needs to have a valid SPF record for the domain (in DNS as a "TXT" record type for sure and add an additional  "SPF" type record if possible).  Why? That's header field being used for spam checks.

2) You should also use a domain key or DKIM.  The trick here is that the domain key/DKIM is case sensitive!  I used Cpanel to create my domain key which automatically used all lowercase domain names in the key creation.  I found when  sending email and using a camel case "-f account@MyDomainHere.Com" option, my key was not accepted.  However it was accepted when I used "-f account@mydomainhere.com".

There are many other factors that can contribute to mail not getting to inboxes, including your own multiple failed testing attempts, so I suggest you consult each site's guidelines and don't ask me for help.  These are just the couple technical issues that helped my case.

I hope this saves someone some time and headaches...
up
-2
Marc Parillo
2 years ago
If you follow the suggested format for the $to field, you can list multiple addresses in a comma-delimited string with spaces.

The spaces could be an issue if you're experiencing a similar problem.  I was unable to send an e-mail to multiple addresses using that format.  It started working for me when I removed all of the spaces in the $to string.

Example:
<?php
$to
= 'nobody@example.com,anotheruser@example.com,yetanotheruser@example.com'; // no spaces
mail($to, 'the subject', 'the message');
?>
up
-1
Joost Brugman
1 year ago
When using mail() under a windows installation (tested under Xampp 1.7.7) any line in $headers that is (between the first and last properly formatted mail header and not a properly formatted mail headers itself) or (that is empty) is removed. As a result MIME formatted messages get scrambled. I am not sure if this behaviour is by design, but this is what it seems to do.

Example $headers:
01 From: "me" <me@domain.com>
02 MIME-Version: 1.0
03 Content-Type: multipart/mixed;
04         boundary=streamline503e8a5d00efdMessage
05
06 --streamline503e8a5d00efdMessage
07 Content-Type: multipart/alternative;
08         boundary=streamline503e8a5d00efdBody
09
10 --streamline503e8a5d00efdBody
11 Content-Type: text/plain;
12         charset=UTF-8
13 Content-Transfer-Encoding: quoted-printable
14
15 This message is written in HTML only.
16
17 --streamline503e8a5d00efdBody
18 Content-Type: text/html;
19         charset=UTF-8
20 Content-Transfer-Encoding: quoted-printable
21
22 This is an email with <b>html</b>content
23 --streamline503e8a5d00efdBody--
24
25 --streamline503e8a5d00efdMessage--
26
27 .

Here, lines 05, 09, 10, 14, 15, 16, 17 are removed. The first properly formatted mail header is on line 01. The last properly formatted mail header is on line 20. The before mentioned entries are between 01 and 20, not properly formatted mail headers themselves and are therefore removed.
Also, lines 21, 24, 26 are removed because they are empty.

As a result this message will be delivered, but the mime structure is broken, since relevant lines are left out.

The solution is to pass lines 01 through 04 in $headers and to pass 06 through 26 to $message. $message will passed unchanged and the mime structure will remain intact.
up
-1
geeralo at gmx dot de
2 years ago
Hello programmers!

There is something important I want to notice about charsets here:

"Content-Type: text/plain; charset = \"UTF-8\";\n"

is right and not only

"Content-Type: text/plain; charset=UTF-8\n"

Hope I could help other people who frustrate while searching the same mistake like me.

Remember also to write only \r for windows and not for Linux-Servers.
And at the end of the header should be an extra blank line:

$headers .= "Content-Type: text/plain; charset = \"UTF-8\";\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$headers .= "\n";

Greetings
up
-1
buraks78 at gmail dot com
3 years ago
If you are having problems changing the Sender and Return-Path headers, make sure that you are editing the right configuration file. On my CentOS 5.6:

[root@server mail]# ll /usr/sbin/sendmail
lrwxrwxrwx 1 root root 21 Oct 26  2009 /usr/sbin/sendmail -> /etc/alternatives/mta
[root@server mail]# ll /etc/alternatives/mta
lrwxrwxrwx 1 root root 23 Apr  9 07:48 /etc/alternatives/mta -> /usr/sbin/sendmail.exim
[root@server mail]# ll /usr/sbin/sendmail.exim
lrwxrwxrwx 1 root root 4 Apr  9 07:45 /usr/sbin/sendmail.exim -> exim

I spent some time trying to figure out why my changes to the sendmail.mc file were being ignored. Naturally, Exim configuration is different than Sendmail. You need to edit the /etc/exim/exim.conf file instead:

remote_smtp:
  driver = smtp
  return_path = bounce@example.com
  headers_rewrite = apache@* info@example.com s

^ Don't forget the "s" at the end. See this page for more information: http://www.exim.org/exim-html-2.00/doc/html/spec_32.html#SEC669

If you are OK with displaying the apache user name (ie "Sender: apache@subdomain.example.com") in the email header, then just update the qualify_domain configuration option in the same file.

qualify_domain = example.com

This will fix the domain only (ie "Sender: apache@example.com").
up
-1
jonte at macnytt dot com
9 years ago
Users of Mac OS X Server need to activate SMTP part of the Mailserver before this is working.

Also note that if the ISP has blocked port 25 outgoing, you run into problems. You can find more info about this in the SMTP server log in Server Admin application if you run OSX Server.
up
-1
nospam at mingo dot ath dot cx
10 years ago
If you're using a linux server using Postfix, and your server hasn't the host name set to a valid name (because it's behind a firewall in an intranet), it's possible that when sending mails using the mail function, some mail servers reject them. This is because they can't check the return path header. If you want to change the Return-Path used by sendmail init the php.ini and edit the sendmail_path variable to this:

sendmail_path = "sendmail -t -i -F webmaster@example.com -f webmaster@example.com"
up
-1
php at caves dot org dot uk
5 years ago
Setting an envelope-sender address avoids mail bounces annoying your system administrator.

If your mail cannot be delivered, it will be rejected to the address specified as the "SMTP-envelope-from" (or the "envelope sender" or "return path", depending on the terminology you like to use )

If you do not explicitly set an envelope-from address then PHP will default to the php.ini setting which - if you have not set this yourself - could be nobody@[your-ISP-domain] or anonymous@[your-ISP-domain], for example.

To avoid bothering the person at that address - or indeed, if you are wondering why you are not receiving mail rejections yourself - you should use the "-f" option in the <$additional_parameters> argument to set a valid address.

(and, by the way: If you do this, but you do not set a From: address in the <$additional_headers> argument then PHP will set a default From: address of "From: Nobody <your-envelope-sender-setting>". ).
up
-1
Max AT
2 years ago
To define a mail sensitivity you have to put this line in the headers:

<?php
        $headers
= "MIME-Version: 1.0\n" ;
       
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";

       
$headers .= "Sensitivity: Personal\n";

$status   = mail($to, $subject, $message,$headers);
?>

Possible Options:
Sensitivity: Normal, Personal, Private and Company-Confidential

These will be recognised and handled in Outlook, Thunderbird and others.
up
-1
saganwebdesign
2 years ago
If you are getting frustrated that your email is being sent as plain text instead of HTML, typically one of your headers showing up in the email (even if other scripts on the same server seem to work fine!!!) then structure your headers like this:

<?php
$headers
= 'From: You <you@example.com>' . "\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
?>

Notice that the From is before the MIME and Content and only Content ends with "\r\n", the other are just "\n"

Not sure how it is possible for other scripts on the same server, same domain to work fine as shown in the very top instructions, and others need this crap... I spent a very frustrating couple hours figuring this out, hope you can avoid doing the same.
up
-1
Clayton Ginsburg
5 years ago
I recently had an issue where the mail() function would work fine from the php cli but not from apache.

I eventually traced this down to the fact that I was using apparmor

Specifically, I configured apparmor to deny the apache user the ability to use /bin/dash

After changing apparmor to /bin/dash rix
and reloading the apparmor profile, mail worked

In other words, mail requires the account/program executing the script to be able to use /bin/dash

I hope this helps someone
up
-1
Gianluigi_Zanettini-MegaLab.it
7 years ago
Please note that using an address in this format "Zane, CEO - MegaLab.it" <myaddrr@mydomain> (" are needed due to comma) works as expected under *nix, but WON'T WORK under Windows.

This is an example

<?php
mail
("\"Zane, CEO - MegaLab.it\" <myaddrr@mydomain>", "prova da test_zane", "dai funziona...");
?>

It works under *unix, but it doensn't under Win: different error are reported:

Warning: mail() [function.mail]: SMTP server response: 553 5.0.0 <"Zane>... Unbalanced '"'

Warning: mail() [function.mail]: SMTP server response: 501 5.5.4 Invalid Address
up
-1
bigtree at dontspam dot 29a dot nl
7 years ago
Since lines in $additional_headers must be separated by \n on Unix and \r\n on Windows, it might be useful to use the PHP_EOL constant which contains the correct value on either platform.

Note that this variable was introduced in PHP 5.0.2 so to write portable code that also works in PHP versions before that, use the following code to make sure it exists:

<?php
if (!defined('PHP_EOL')) define ('PHP_EOL', strtoupper(substr(PHP_OS,0,3) == 'WIN') ? "\r\n" : "\n");
?>
up
-1
johniskew2
7 years ago
An important rule of thumb, because it seems few really follow it and it can alleviate so many headaches: When filtering your email headers for injection characters use a regular expression to judge whether the user's input is valid.  For example to see if the user entered a valid e-mail address use something like  [a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}.  Dont try to filter out bad characters (like searching for LF or CR), because you will ALWAYS miss something.  You can be sure your application is more secure going this route....provided the regular expression is valid!  This same point goes for any sort of form input not just for sending out emails.
up
-1
fontajos at phpeppershop dot com
8 years ago
Problems with Microsoft Exchange and PHP as ISAPI-module

We found out, that if you want to send multipart mime emails using the PHP mail-function on a Windows box using a Microsoft Exchange server, you have to use separate containers for the mail body and the mail header.

In many examples like in http://www.zend.com/zend/trick/html-email.php or in the book PHP developers cookbook you find html multipart/alternative mailing solutions that build the mime header and the mail body into one PHP variable and send this as fourth argument (header) to the PHP mail-function. This works fine on most systems but not on the above mentioned combination.

We found a rather trivial solution: Simply split the mime mail header and the mail body into two separate variables and give them separately to the PHP mail function, example:

<?php
//add From: header
$headers = "From: webserver@localhost\r\n";

//specify MIME version 1.0
$headers .= "MIME-Version: 1.0\r\n";

//unique boundary
$boundary = uniqid("HTMLDEMO");

//tell e-mail client this e-mail contains//alternate versions
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

//plain text version of message
$body = "--$boundary\r\n" .
  
"Content-Type: text/plain; charset=ISO-8859-1\r\n" .
  
"Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode("This is the plain text version!"));

//HTML version of message
$body .= "--$boundary\r\n" .
  
"Content-Type: text/html; charset=ISO-8859-1\r\n" .
  
"Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode("This the <b>HTML</b> version!"));

//send message
mail("root@localhost", "An HTML Message", $body, $headers);
?>
up
-1
benles at bldigital dot com
9 years ago
I get a 550 error when using mail() with this To format:

User <user@example.com>

When it's changed to just the bare email, it works fine. Just FYI that some mail servers may behave this way.
up
-2
sander at cartel dot nl
8 years ago
I found out that a ms server (ESMTP MAIL Service, Version: 5.0.2195.6713) also had the problem using CRLF in the headers:

If messages are not received, try using a LF (\n) only. Some poor quality Unix mail transfer agents replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with RFC 2822.

The suggested fix works.

Sander
up
-2
Maven1 at example dot com
4 years ago
I was having trouble with the newline and carriage return characters when using the mail function in a custom script within Joomla since the stupid input validations kept stripping them (changed "/r/n" to "rn").

To get around this, I used chr(13) and chr(10) to insert them.

<?php

$headers
.= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . chr(13) . chr(10);
$headers .= 'From: Birthday Reminder <birthday@example.com>' . chr(13) . chr(10);

?>

Hope that helps someone.
up
-2
GwarDrazul
8 years ago
The article mentioned below is quite good to understand the problem of header injection. However, it suggests the following as a solution: look for "\n" and "\r" inside your user input fields (especially in those used for the $header param) and, if found reject the mail.

Allthough this will probably work I still believe it is better to have a "white list" of allowed characters instead of a "black list" with forbidden characters.

Example:
If you want a user to enter his name, then allow characters only!
If you want a user to enter his email adress, then check if the entry is a valid email adress.

Doing so might automatically solve problems which you didn't think of when you created the "black list". For SMTP headers colons are needed. If you check for a valid email adress the hacker won't be able to enter colons inside that form field.

I suggest using regular expressions for those checks.

For more information about regular expressions see:
http://www.regular-expressions.info/
up
-5
krzysiek dot 333 at gmail dot com
3 years ago
Sending messages with polish special characters:
<?php
function plmail($mail, $sub, $mes){
   
$headers = "From: ExRobot <robot@example.com>\r\n";
   
$headers .= "MIME-Version: 1.0\r\n";
   
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
   
$headers .="Content-Transfer-Encoding: 8bit";
   
   
$mes=htmlspecialchars_decode($mes,ENT_QUOTES);//optional - I use encoding to POST data
   
mail($mail, "=?utf-8?B?".base64_encode($sub)."?=", $mes, $headers);
}
?>
Page must be in utf-8 encoding.
up
-1
Tobias Christensen
8 months ago
It might be good to know, that you might get some Header error using the boundary, if it's not done correctly.

I got the header error about wrong close of the boundary, which in my case wasn't what was really wrong.

The thing to fix this might be to give the header before this a "\n\r", which might fix it.

For my case I needed to this twice, as I am doing this as strings, but as arrays and implodes them at the end with the "\n\r". I did it also in the specific header array, where the boundary is generated.
up
-1
bburch at bouncingpixel dot com
1 year ago
When using the PHP mail() function with IIS 6 on Windows Server 2003, check your "Relay" settings on the SMTP Virtual Server in IIS.  If you grant access to 127.0.0.1 and set then set your php.ini SMTP to the same IP address (along with setting the same port 25), you should have success in sending mail. 

I'm using PHP 5.3 and have had success with this configuration and did not have to define the "sendmail_from" setting in our php.ini file.
up
-1
phadley at reliableid dot com
4 years ago
The mail function will stop including headers if you misspell one of them.  It doesn't report an error, it just puts the offending header and all that follow it in the body of the message.  My great transgression was using MIME Version instead of MIME-Version, a lapse which cost me several hours.
up
-1
rch+php at online dot lt
4 years ago
RFC-2822 is quite explicit, that "Though some message   systems locally store messages in this format (which eliminates the need for translation between formats) and others use formats that differ from the one specified in this standard, local storage is outside of the scope of this standard."

And it is not just "some", but most Unix mailers choke when you try pipe CRLF instead of Unix line endings to "sendmail" command.  PHP is using line endings as is, so you have better chances for success if you use Unix file format or line endings.
up
-1
dtbaker.com.au
4 years ago
An observation about safe_mode and mail()

It looks like multiple \r\n's are replaced by a single \r\n inside the string passed to "additional_headers". I can only re-produce this on a box running with safe_mode enabled.

If (for some reason) your script crafts the entire email message in the headers, this will most likely produce a blank email on safe_mode boxes (like this script I've been trying to get working).
up
-2
mulllhausen
3 years ago
i found that emails were not getting sent when i specified multiple recipients separated by commas in the $to variable.

however i did find that i could specify multiple recipients using the the 'To: ' header. i am using php cli on ubuntu 10.04.1 lts.

hopefully this is useful to someone
up
-1
d dot r at usask dot ca
5 years ago
The example indicates \r\n at the end of each line in the headers but this was causing me problems as emails showed some of the headers as part of the body.  I simply used only \n as in some of the other examples and the problem went away.
up
-2
matthew dot mckay at uwrf dot edu
4 years ago
Note: On some windows platforms this is NOT thread safe.
We are having email message bodies being sent out to the wrong headers multiple times, some failing to send, and other bizarre stuff. If you google search for "php mail thread safe" you can find a ton of relevant information.
This is not a bug in php, there have been multiple bugs closed with this issue being dismissed as not an issue with PHP.
up
-3
epheterson at gmail dot com
3 years ago
After banging my head against the wall, I realized after my host updated PHP that the From line in the header requires quotes around the name where before it worked regardless. Otherwise it will report success, and not sent.

$headers .= 'From: "'. $Name . '" <' . $Email . '>' . "\r\n";
up
-2
aldertb at XS4ALL dot nl
5 years ago
I experienced problems with removed euro signs and some other accented letters. The text came from a DB but contained the euro sign etcetera inside the mail function, just as when you would define it as a string. (Did die($newsletter['message']). It was lost in the mail I received though! When I defined the message as a string inside the sending function (overriding text from DB), including euro sign as a single character, I DID receive the email including euro sign!

This was experienced on 2 different email accounts. With one I received no text after the euro sign.

But only when text came from mySQL DB from a longtext Latin1-field...

I installed the pear mail class and this solved the strange problem and could just send text from the DB...
up
-2
php at ontheroad dot net dot nz
5 years ago
Another possible cause for the "501 5.5.4 Invalid Address" type errors when sending mail from Windows is specifying BCC or CC parameters with no value.
up
-1
Ben Cooke
8 years ago
Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your  message and headers must use the standard line endings \r\n as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any \n to \r\n, so you must supply only \n to mail() on a UNIX system to avoid the MTA hypercorrecting to \r\r\n.

If you use plain old \n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely \n without an accompanying \r.
up
-1
grey at greywyvern dot moc
9 years ago
When including your own custom headers try not to include a trailing \r\n at the end of the last header.  Leaving the \r\n causes an extra line-feed at the beginning of the message body, so your message will start on the second line.
up
-2
Anonymous
9 years ago
A co-worker of mine had a problem where she needed to have a backslash in the header. Basically, the name of the company has a couple of backslashes in it. However, when the recipient was receiving the email, the "From:" part had the backslashes removed. We got it to work but placing three backslashes whenever we wanted one to show up. I'd assume that the mail server was modifying the headers and this is not really an issue with php. Anyway, thought this might help someone.
up
-1
f dot touchard at laposte dot net
11 years ago
***Encoding plain text as quoted-printable in MIME email***

If you don't want to install IMAP and use imap_8bit() to encode plain text or html message as quoted-printable
(friendly french special characters encoding :-) in MIME email, try this function.
I haven't fully tested it ( like with microtime with long mails). I send html message as 7-bit, so I didn't try yet with html.
If you have good html practise, you don't really need to encode html as quote-printable as it only uses 7-bit chars.
F.Touchard

<?php
function qp_encoding($Message) {
   
   
/* Build (most polpular) Extended ASCII Char/Hex MAP (characters >127 & <255) */
   
for ($i=0; $i<127; $i++) {
       
$CharList[$i] = "/".chr($i+128)."/";
       
$HexList[$i] = "=".strtoupper(bin2hex(chr($i+128)));
    }

   
/* Encode equal sign & 8-bit characters as equal signs followed by their hexadecimal values */
   
$Message = str_replace("=", "=3D", $Message);
   
$Message = preg_replace($CharList, $HexList, $Message);

   
/* Lines longer than 76 characters (size limit for quoted-printable Content-Transfer-Encoding)
        will be cut after character 75 and an equals sign is appended to these lines. */
   
$MessageLines = split("\n", $Message);
   
$Message_qp = "";
    while(list(,
$Line) = each($MessageLines)) {
        if (
strlen($Line) > 75) {
           
$Pointer = 0;       
            while (
$Pointer <= strlen($Line)) {
               
$Offset = 0;
                if (
preg_match("/^=(3D|([8-9A-F]{1}[0-9A-F]{1}))$/", substr($Line, ($Pointer+73), 3))) $Offset=-2;
                if (
preg_match("/^=(3D|([8-9A-F]{1}[0-9A-F]{1}))$/", substr($Line, ($Pointer+74), 3))) $Offset=-1;
               
$Message_qp.= substr($Line, $Pointer, (75+$Offset))."=\n";
                if ((
strlen($Line) - ($Pointer+75)) <= 75) {               
                   
$Message_qp.= substr($Line, ($Pointer+75+$Offset))."\n";
                    break
1;
                }
               
$Pointer+= 75+$Offset;
            }
        } else {
           
$Message_qp.= $Line."\n";
        }
    }       
    return
$Message_qp;
}
?>
up
-2
Sven Riedel
10 years ago
mail() requires /bin/sh to exist in Unix environments, next to a mail delivery program. This is very relevant when setting up apache in a chroot environment. Unfortunately this isn't anywhere in the documentation and took me several months to figure out.
up
-2
stevenlim at Edinburgh-Consulting dot com
11 years ago
How to detect a bounce email

1. make sure the email you send out have the header
"Return-Path: detect-bounce@example.com\r\n",
&
"Return-Receipt-To: bounce@example.com\r\n"

2. setup this detect-bounce mail account at your mail server

3. redirect the incoming mail from this email account to your php script (check your mail server doc on how do this)

4. your php script will then be able to process the incoming email in whatever way you like, including to detect bounce mail message (use regexp search).

Note that the mail will be not be store after the mail server has redirect to your script.  If you want to store it, you need additional code in your script

Hope the above help

Steven Lim
IT Consultant
up
-3
webmaster at plumage dot nl
5 years ago
The work-around for a large quantity of recipients is putting the adresses in the header-section as Bcc adresses.
In this way the mail()-function opens and closes the SMTP connection only once:

<?php
$count_recip
= count($recip);//where $recip represents an array of mail-adresses, from MySql-query or otherwise
$count='0';
$headers.="Bcc: ";
while(
$count < $count_recip){
$headers.=$recip[$count].", ";
$count ++;
}
$headers.="admin@example.com\r\n";
?>
up
-3
Alex Jaspersen
7 years ago
For qmail users, I have written a function that talks directly to qmail-queue, rather than going through the sendmail wrapper used by mail(). Thus it allows more direct control over the message (for example, you can adapt the function to display "undisclosed recipients" in to the To: header). It also performs careful validation of the e-mail addresses passed to it, making it more difficult for spammers to exploit your scripts.

Please note that this function differs from the mail() function in that the from address must be passed as a _separate_ argument. It is automatically put into the message headers and _does not_ need to be included in $additional_headers.

$to can either be an array or a single address contained in a string.
$message should not contain any carriage return characters - only linefeeds.

No validation is performed on $additional_headers. This is mostly unnecessary because qmail will ignore any additional To: headers injected by a malicious user. However if you have some strange mail setup it might be a problem.

The function returns false if the message fails validation or is rejected by qmail-queue, and returns true on success.

<?php
function qmail_queue($to, $from, $subject, $message, $additional_headers = "")
{
   
// qmail-queue location and hostname used for Message-Id
   
$cmd = "/var/qmail/bin/qmail-queue";
   
$hostname = trim(file_get_contents("/var/qmail/control/me"));
   
   
// convert $to into an array
   
if(is_scalar($to))
       
$to = array($to);
   
   
// BEGIN VALIDATION
    // e-mail address validation
   
$e = "/^[-+\\.0-9=a-z_]+@([-0-9a-z]+\\.)+([0-9a-z]){2,4}$/i";
   
// from address
   
if(!preg_match($e, $from)) return false;
   
// to address(es)
   
foreach($to as $rcpt)
    {
        if(!
preg_match($e, $rcpt)) return false;
    }
   
   
// subject validation (only printable 7-bit ascii characters allowed)
    // needs to be adapted to allow for foreign languages with 8-bit characters
   
if(!preg_match("/^[\\040-\\176]+$/", $subject)) return false;
   
   
// END VALIDATION
   
    // open qmail-queue process
   
$dspec = array
    (
        array(
"pipe", "r"), // message descriptor
       
array("pipe", "r") // envelope descriptor
   
);
   
$pipes = array();
   
$proc = proc_open($cmd, $dspec, $pipes);
    if(!
is_resource($proc)) return false;
   
   
// write additional headers
   
if(!empty($additional_headers))
    {
       
fwrite($pipes[0], $additional_headers . "\n");
    }
   
   
// write to/from/subject/date/message-ID headers
   
fwrite($pipes[0], "To: " . $to[0]); // first recipient
   
for($i = 1; $i < sizeof($to); $i++) // additional recipients
   
{
       
fwrite($pipes[0], ", " . $to[$i]);
    }
   
fwrite($pipes[0], "\nSubject: " . $subject . "\n");
   
fwrite($pipes[0], "From: " . $from . "\n");
   
fwrite($pipes[0], "Message-Id: <" . md5(uniqid(microtime())) . "@" . $hostname . ">\n");
   
fwrite($pipes[0], "Date: " . date("r") . "\n\n");
   
fwrite($pipes[0], $message);
   
fwrite($pipes[0], "\n");
   
fclose($pipes[0]);
   
   
// write from address and recipients
   
fwrite($pipes[1], "F" . $from . "\0");
    foreach(
$to as $rcpt)
    {
       
fwrite($pipes[1], "T" . $rcpt . "\0");
    }
   
fwrite($pipes[1], "\0");
   
fclose($pipes[1]);
   
   
// return true on success.
   
return proc_close($proc) == 0;
}
?>
up
-3
admin at chatfamy dot com
7 years ago
One thing it can be difficult to control with this function is the envelope "from" address. The envelope "from" address is distinct from the address that appears in the "From:" header of the email. It is what sendmail uses in its "MAIL FROM/RCPT TO" exchange with the receiving mail server. It also typically shows up in the "Return-Path:" header, but this need not be the case. The whole reason it is called an "envelope" address is that appears _outside_ of the message header and body, in the raw SMTP exchange between mail servers.

The default envelope "from" address on unix depends on what sendmail implementation you are using. But typically it will be set to the username of the running process followed by "@" and the hostname of the machine. In a typical configuration this will look something like apache@box17.example.net.

If your emails are being rejected by receiving mail servers, or if you need to change what address bounce emails are sent to, you can change the envelope "from" address to solve your problems.

To change the envelope "from" address on unix, you specify an "-r" option to your sendmail binary. You can do this globally in php.ini by adding the "-r" option to the "sendmail_path" command line. You can also do it programmatically from within PHP by passing "-r address@example.com" as the "additional_parameters" argument to the mail() function (the 5th argument). If you specify an address both places, the sendmail binary will be called with two "-r" options, which may have undefined behavior depending on your sendmail implementation. With the Postfix MTA, later "-r" options silently override earlier options, making it possible to set a global default and still get sensible behavior when you try to override it locally.

On Windows, the the situation is a lot simpler. The envelope "from" address there is just the value of "sendmail_from" in the php.ini file. You can override it locally with ini_set().
up
-2
Michiel Uitdehaag
3 years ago
We had a LAMP setting with postfix as mail system. Our additional headers were not interpreted correctly by a receiving mailserver (Exchange/ENOD32) and a newline was inserted after the first additional header.

It turns out that a internet/dos style newline (\r\n) in the headers were converted to \r\r\n (ie: something mindlessly replaced all \n with \r\n without seeing if \n was already preceded by \r)

I don't know if this is something in PHP or postfix, but seeing the comments below I suspect it is something of PHP on *NIX in combination with non-sendmail mailers.

So, use your 'local' newline style for additional headers, as opposed to the examples above.

I don't know if this is a bug anywhere. I don't know which element exactly does the unix2dos translation. If it is PHP, it should only replace ([^\r])\n  with \1\r\n
up
-2
Systemx
4 years ago
Bare LFs in SMTP

Use This

<?php
// Fix any bare linefeeds in the message to make it RFC821 Compliant.
$message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);
   
// Make sure there are no bare linefeeds in the headers
$headers = preg_replace('#(?<!\r)\n#si', "\r\n", $headers);
?>
up
-2
Tomer
5 years ago
I was trying to create a script that would send large forms without having to get/post each value first and came up with this... should help someone to save valuable time.

<?php
$emailSentTo
= "";
$subjectOfEmail = "";

//========= no need to edit bellow

// Set HTML Mail Header
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// The Message
$message = $GLOBALS["HTTP_SERVER_VARS"]["REQUEST_URI"];

//Cleaning Message
$message = str_replace('?','<br><hr>',str_replace('/','File used for submittimg this form: ',str_replace('=',': ',str_replace('&','<br>',$message))));

// Sending
mail($emailSentTo, $subjectOfEmail, $message, $headers);

//Thanking
echo "<script language=\"javascript\" type=\"text/javascript\">
alert('Thank You, We will contact you shortly.');
window.location = \"http://
$_SERVER[HTTP_HOST]\";
</script>
"
;
?>
up
-2
Anonymous
5 years ago
I was (finally) able to get multipart HTML mail working.
The 'boundary' must be defined with double quotes, not apostrophes.

$headers .= "Content-Type: multipart/alternative;boundary=\"$boundary\";\n\n";
up
-2
alex_ramos at sourceforge dot net
5 years ago
Beware if you're trying to use "-f" or "-r" with the 5th parameter of the PHP mail() function, and you're relying on a plain vanilla install of sendmail on Linux, it won't work. You'll have to either change the sendmail config and add your script's userid to "trusted-users" (easier said than done... good luck with that!), or, remove sendmail and install postfix (much easier).
up
-2
bob
6 years ago
If the Cc or Bcc lines appear in the message body, make sure you're separating header lines with a new line (\n) rather than a carriage return-new line (\r\n). That should come at the very end of the headers.
up
-2
phpcoder at cyberpimp dot ig3 dot net
6 years ago
In addition to the $to parameter restrictions on Windows (ie. address can not be in "name <user@example.com>" format), the same restrictions apply to the parsed Cc and Bcc headers of the $additional_headers parameter.

However, you can include a To header in $additional_parameters which lists the addresses in any RFC-2822 format.  (For display purposes only.  You still need to list the bare addresses in the $to parameter.)
up
-4
Alex M.
4 years ago
It is important to filter the form input to prevent header injection. Here is a simple way:

<?php
# Anti-header-injection - Use before mail()
# By Victor Benincasa <vbenincasa(AT)gmail.com>

foreach($_REQUEST as $fields => $value) if(eregi("TO:", $value) || eregi("CC:", $value) || eregi("CCO:", $value) || eregi("Content-Type", $value)) exit("ERROR: Code injection attempt denied! Please don't use the following sequences in your message: 'TO:', 'CC:', 'CCO:' or 'Content-Type'.");
?>

--
Alex M.
up
-4
orjtor
5 years ago
This is my solution of problems with Windows Mail on Vista. I got some of the headers in the mail body as plain text. When I removed '\r' and left just '\n' at the end of the two last lines of header it worked. This error didn't show up in my yahoo mail.
<?php
    $body
= "<html>\n";
   
$body .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif; font-size:12px; color:#666666;\">\n";
   
$body = $message;
   
$body .= "</body>\n";
   
$body .= "</html>\n";
   
   
$headers  = "From: My site<noreply@example.com>\r\n";
   
$headers .= "Reply-To: info@example.com\r\n";
   
$headers .= "Return-Path: info@example.com\r\n";
   
$headers .= "X-Mailer: Drupal\n";
   
$headers .= 'MIME-Version: 1.0' . "\n";
   
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
   
    return
mail($recipient, $subject, $message, $headers);
?>
up
-2
Paul
10 years ago
My mime multipart/alternative messages were going ok, until I switched to qmail with php .. after years of painfull searching, I came across this on the Life With Qmail 'Gotchas' section:

G.11. Carriage Return/Linefeed (CRLF) line breaks don't work

qmail-inject and other local injection mechanisms like sendmail don't work right when messages are injected with DOS-style carriage return/linefeed (CRLF) line breaks. Unlike Sendmail, qmail requires locally-injected messages to use Unix newlines (LF only). This is a common problem with PHP scripts.

So now, I can go back to sending emails with text AND html components :)
up
-4
fnjordy at gmail dot com
8 years ago
Another example of sending a utf-8 HTML mail:

<?php
$to
= 'bob@example.com';
$subject = 'Wakeup bob!';
$message = '<b>yo</b>, whassup?';
$headers = "From: server@example.com\r\n" .
       
'X-Mailer: PHP/' . phpversion() . "\r\n" .
       
"MIME-Version: 1.0\r\n" .
       
"Content-Type: text/html; charset=utf-8\r\n" .
       
"Content-Transfer-Encoding: 8bit\r\n\r\n";

// Send
mail($to, $subject, $message, $headers);
?>
up
-5
marcel dot portela at gmail dot com
5 years ago
To define a mail priority you have to put this lines in the headers:

<?php
        $headers
= "MIME-Version: 1.0\n" ;
       
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
       
$headers .= "X-Priority: 1 (Higuest)\n";
       
$headers .= "X-MSMail-Priority: High\n";
       
$headers .= "Importance: High\n";

$status   = mail($to, $subject, $message,$headers);
?>

Here i've added many headers information including the Priority...
up
-3
ittasks at gmail dot com
1 year ago
When dealing with mail headers "\n" and "\r\n" *sometimes* makes a big difference.

Once our CentOs servers got re-installed, all headers like:

  $headers = "MIME-Version: 1.0\r\n";
  $headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
...

became part of message body instead of headers

I was able to fixed this by replacing "\r\n" with just "\n"
up
-5
Josh
7 years ago
While trying to send attachments I ran into the problem of having the beginning part of my encoded data being cut off.

A fact that I didn't see mentioned anywhere explicitly (except maybe in the RFC, which admittedly I didn't read fully) was that two newlines are required before you start the encoded data:

Content-Transfer-Encoding: base64\n
Content-Type: application/zip; name="test_file.zip"\n
\n  //<--- if this newline isn't here your data will get cut off
DATA GOES HERE
up
-3
mortoray at ecircle-ag dot com
6 years ago
Apparently if using the mbstring library, and using overriden functions, the "mail" command appears to use "Content-Transfer-Encoding: BASE64" by default.  Which if you combine it with PEAR Mail_Mime you'll get mails that, although they appear RFC compliant, not mailer can read correctly.

To fix this it appears you should add a fixed header in the mail command (this one assumes the pear mime module is 7bit clean, perhaps 8bit would also be fine)

<?php $headers['Content-Transfer-Encoding'] = '7bit'; ?>
up
-3
tdaniel at univ dot haifa dot ac dot il
7 years ago
I had trouble getting multiple emails sent for Outlook accounts (a single PHP page performed 2 mail() calls).

The PHP mail() function works correctly, but the same mails that were recieved on a private POP3 server were randomly missing by our intranet Outlook exchange server.

If you have the same problem, try to verify that the "Message-ID: " is unique at the $headers string. i.e.

<?php
$headers
= [...] .
"Message-ID: <". time() .rand(1,1000). "@".$_SERVER['SERVER_NAME'].">". "\r\n" [...];
?>

(rand() is used only for demonstration purposes. a better way is to use an index variable that increments (i++) after each mail)

I noticed that when multiple messeges were sent simultaneously, the message-id was the same (probably there was no miliseconds differential). My guess is that Outlook is collating messages with the same message-ID; a thing that causes only one email to pass to the Outlook inbox instead of a few.
up
-3
Nimlhug
8 years ago
As noted in other, well, notes; the "additional headers" parameter can be easily exploited, when doing things like:

<?php
  mail
( $_POST['to'], $_POST['subject'], $_POST['message'], 'Reply-to: '.$_POST['from']."\r\n" );
?>

An easy way of fixing this, is removing CRLFs from the header-strings, like so:

<?php
  $_POST
['from'] = str_replace( "\r\n", '', $_POST['from'] );
?>

This way, the extra data will be part of the previous header.
up
-3
junaid at techni-serve dot com
8 years ago
Note: on class "multipartmail".  Modify the function buildmessage with the following and it will work great.

function buildmessage(){
         $this->message = "This is a multipart message in mime format.\n";
         $cnt = count($this->parts);
         for($i=0; $i<$cnt; $i++){
           $this->message .= "--" . $this->boundary . "\n" .$this->parts[$i];
         }
        $this->message .= "--" . $this->boundary . "-- \n";
     }

Thank for all the help.
up
-5
akger1379 at gmail dot com
2 years ago
Use sendmail in queue mode to prevent long pauses everytime php is calling the mail() function.

<?php
$additionalParameters
= '-ODeliveryMode=d';
mail($to, $subject, $message, $headers, $additionalParameters);
?>

Your mails will be delivered everytime the sendmail daemon is processing the queue. To see what the interval may be see the "QUEUE_INTERVAL" variable in /etc/mail/sendmail.conf
up
-5
debis at woh dot rr dot com
2 years ago
This is for Windows Server 2003, IIS 6.0 with SMTP virtual server.

The problem I had was not including init_set for the SMTP server, I thought the SMTP definition in the IIS SMTP virtual server configuration would work.  When I sent mail manually this was not an issue. 

Also, $mail_sent = @mail( $to, $subject, $message, $headers ); wouldn't work but $mail_sent = mail($to, $subject, $message, $headers); did.
Lack of date_default_timezone_set() only caused a warning because php guessed what it should be.

This worked:
<?php
$to     
= 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
   
'Reply-To: webmaster@example.com' . "\r\n" .
   
'X-Mailer: PHP/' . phpversion();
ini_set ( "SMTP", "smtp-server.example.com" );
date_default_timezone_set('America/New_York');

mail($to, $subject, $message, $headers);
?>

And just so you can troubleshoot, this worked when sending mail from the command line/manually. CLI worked even though the php code without the init_set function wouldn't work.

You will notice that the "rcpt to" and "to" fields appear redundant, but if both are not used, the delivered mail's "to" field will be blank/empty.

-------------------------------
telnet www.example.com 25
helo
mail from: webmaster@example.com
rcpt to: someone@example.com
data
to: someone@example.com
subject: test again to make sure

this is my message
.
quit
-----------------------------------
up
-8
me at arronwoods dot com
3 years ago
I've had all sorts of problems with scripts that don't set the "-f user@example.org" parameter when using mail() if postfix is the sendmail agent.

In postfix I had SMTP relay authentication based on the sender address, but it was always the PHP user as the sender until I adapted the code from:

<?php mail('test@example.org', 'Subject', 'Body', 'From: user@example.org'); ?>

to:

<?php mail('test@example.org', 'Subject', 'Body', 'From: user@example.org', '-f user@example.org'); ?>

I couldn't find a way to adjust PHP or Postfix to do this for me, so I had to edit the application. I was actually using Zend_Mail_Transport_Smtp, which made it that little bit trickier. I ended up with this:

<?php

class My_Mail_Transport_Sendmail extends Zend_Mail_Transport_Sendmail {

    public function
_sendMail() {
        if (
$this->parameters === null) {
           
$this->parameters = '-f ' . $this->_mail->getFrom();
        }

        return
parent::_sendMail();
    }

}
?>
To Top