Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Mail Functions

Mail Functions

Introduction

The mail() function allows you to send mail.

Requirements

For the Mail functions to be available, PHP must have access to the sendmail binary on your system during compile time. If you use another mail program, such as qmail or postfix, be sure to use the appropriate sendmail wrappers that come with them. PHP will first look for sendmail in your PATH, and then in the following: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. It's highly recommended to have sendmail available from your PATH. Also, the user that compiled PHP must have permission to access the sendmail binary.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table156.Mail configuration options

Name Default Changeable Changelog
SMTP "localhost" PHP_INI_ALL
smtp_port "25" PHP_INI_ALL Available since PHP 4.3.0.
sendmail_from NULL PHP_INI_ALL
sendmail_path "/usr/sbin/sendmail -t -i" PHP_INI_SYSTEM


For further details and definitions of the PHP_INI_* constants, see the AppendixI, php.ini directives.

Here's a short explanation of the configuration directives.

SMTP string

Used under Windows only: host name or IP address of the SMTP server PHP should use for mail sent with the mail() function.

smtp_port int

Used under Windows only: Number of the port to connect to the server specified with the SMTP setting when sending mail with mail(); defaults to 25. Only available since PHP 4.3.0.

sendmail_from string

Which "From:" mail address should be used in mail sent from PHP under Windows. This directive also sets the "Return-Path:" header.

sendmail_path string

Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail. configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if any. For example, Qmail users can normally set it to /var/qmail/bin/sendmail or /var/qmail/bin/qmail-inject.

qmail-inject does not require any option to process mail correctly.

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents

ezmlm_hash — Calculate the hash value needed by EZMLM
mail — Send mail

Code Examples / Notes » ref.mail

mail

[ THIS NOTE IS FOR MY POST ABOUT THE SEND_MAIL() FUNCTION ]
In addition to the already posted PHP Mail-functions, I decided there wasn't one that fitted all my needs, so I wrote my own. I have tested it, and I use it at a Windows 2000 server, but I don't think it won't function at *nix.
Usage:
send_mail(string $MailTo, string $SenderName, string $SenderMail, string $Subject, string-or-path $Mailcontent [, string $Attachment ] [, string $Servername ] [, string $nohtml])
The function returns true or false, depending on if the E-mail has been sent succesfully.
Note 1: $Mailcontent can be a string OR a path to a file.
Note 2: Function works without attachment too
Note 3: Function works to Hotmail
Note 4: Function needs PHP module [ mime_magic ] to detect attachment-type!


krzystu

What about Bounce parameter for sendmail:
"-f $from" as the fifth one. Without that Return-Path will be set to sendmail administrator


ivo fokkema i.fokkema att lumc d0ttt nl

We have a open source project that needed to be able to function on as many platforms and configurations as possible. Using '\n' as end-of-line for emailheaders would probably 'break' the email functionality on Windows and Mac platforms.
I have fixed this using the code below. Please note that since I don't have any access to a Mac server, this setup is not tested on a Mac, but should work.
if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
       $s_eol = "\r\n";
} elseif (strtoupper(substr(PHP_OS, 0, 3) == 'MAC')) {
       $s_eol = "\r";
} else {
       $s_eol = "\n";
}
(Thanx to Eric Gach on http://www.phpbuilder.com/lists/php-windows/2003032/0057.php for the inspiration!)
Then construct your headers using
$s_headers = 'From: registrationform@example.org' . $s_eol;
Hope this helps anyone!!!
Ivo


p_p

This function don`t may replace in the header in the field "envelope-from". It`s no good.

perryv

The ini_set('sendmail_from', $your_from_addr) solution only works when the PHP mailer script is running under Windows. To do a similar solution for *nix OS's, pass the string "-r $your_from_addr" to mail() as the fifth parameter.

br

The example function by nielsvandenberge at hotmail dot com is nice, but some Mail Programs (e.g. Outlook Express, etc) do have problems and do not display any text or html of the mailbody - only as a separate attachment.
The main problem is that the multipart/alternative part is not bounded correctly (a problem that Outlook and other newer mailers seem to ignore). To make the function compatible to older/standard mail-programs simply add a second mime boundary, which marks the bounds of the alternative parts:
<?
 $mime_boundary_2 = "1_".$mime_boundary;
 $msg .= "Content-Type: multipart/alternative; boundary=\"".$mime_boundary_2."\"".$eol;
 
 # Text Version
 $msg .= "--".$mime_boundary_2.$eol;
 $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
 $msg .= strip_tags(str_replace("
", "\n", $body)).$eol.$eol;
 
 # HTML Version
 $msg .= "--".$mime_boundary_2.$eol;
 $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
 $msg .= $body.$eol.$eol;
 
 # New Subboundary Finished
 $msg .= "--".$mime_boundary_2."--".$eol.$eol;
 # Top-Boundary Finished
 $msg .= "--".$mime_boundary."--".$eol.$eol;
?>
The above snippet also corrects the missing second eol after Content-Transfer-Encoding: 8bit.


def

The body of the message cannot, in some (many?) cases, contain "bare line feeds" -- i.e. just "\n".
See this: http://cr.yp.to/docs/smtplf.html


kieran dot huggins

Thanks Hilger - that will come in handy on my end.
Here's a great overview of the MIME spec from 1993:
http://www.mindspring.com/~mgrand/mime.html
Happy mailing! - Kieran


derernst

Suggestion for methods checking form inputs for e-mail injection attempts.
Any inputs expected from single-line text fields can just be refused if they contain a newline character. The second function tries to minimize matches on non-evil inputs by matching suspect strings only if preceded by a newline character. (Anyway, if this is considered to be safe, it will of course do it for single-line inputs, too.)
<?php
/**
* Check single-line inputs:
* Returns false if text contains newline character  
*/
function has_no_newlines($text)
{
   return preg_match("/(%0A|%0D|\\n+|\\r+)/i", $text) == 0;
}
/**
* Check multi-line inputs:
* Returns false if text contains newline followed by
* email-header specific string
*/
function has_no_emailheaders($text)
{
   return preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i", $text) == 0;
}
?>


joe

SpamAssassin flags it as NO_REAL_NAME because it's looking for a real name with the e-mail address...  Instead of passing user@host.com, use "My Name <user@host.com>".  This will stop that particular problem.
Also, if you send messages all in HTML, get familiar with Mail/Mime in pear and strip_tags to send a text message identical to the HTML version.  This takes care of some other SA problems, and makes it easier for people to read from non-gui mailreaders.
And on a final note, to keep Outlook users from automatically marking your messages as Junk Mail, send a message from Outlook to yourself, look at the headers, and make sure you send as many of the same ones as you can.  If outlook thinks your message was sent from another outlook client, it'll score higher on the junk filter.


valeriogiuffrida

Sometimes using that headers:
$header = "Return-Path: lostpass@website.net\n";
$header .= "X-Sender: lostpass@website.net\n";
$header .= "From: This is my website <lostpass@website.net>\n";
$header .= "X-Mailer:PHP 5.1\n";
$header .= "MIME-Version: 1.0\n";
Gmail and Hotmail could consider it as "spam", so I just inserted before to send email:
ini_set(sendmail_from, "lostpass@mywebsite.net");
and ini_restore after it...


grass ät leht dot ee

something that worked for my outlook express...
dnx 4 your code "nielsvandenberge at hotmail dot com
"
but
if you just swich the text part into first and attachment part into second place, Outlook Express 6 reads it just fine
otherwise it creates a textfile of the text content....


d dot g dot clau

Sending mail with php can be quite tricky, especially when mail() is disabled and/or SMTP service is not available. POSS can be the solution, a mail() clone with buil-in MTA, available here: http://poss.sourceforge.net/email/ .

expertphp

Send an e-mail directly to client smtp server in real time.
For more informations, please visit : http://expert.no-ip.org/?free=smtp_mail&func
<?php
@set_time_limit(0);

require_once 'smtp_mail.php';

$to = "expertphp@yahoo.com";
$from = "from@myaccount.com";
$subject = "Subject here";

$headers = "MIME-Version: 1.0\r\n".
   "Content-type: text/html; charset=iso-8859-1\r\n".
   "From: \"My Name\" <".$from.">\r\n".
   "To: \"Client\" <".$to.">\r\n".
   "Date: ".date("r")."\r\n".
   "Subject: ".$subject."\r\n";

$message = "
<html>
<body>
<b>html message</b>
<font color=\"red\">here</font>
<img src=\"http://static.php.net/www.php.net/images/php.gif\"
border=\"0\" alt=\"\">
</body>
</html>
";
$response = smtp_mail($to, $subject, $message, $from, $headers);

if($response[0]) echo "The message has been sent !<br />\n".$response[1];
else echo "The message can not been sent !<br />\n".$response[1];

?>


marek mhling

re: mxcl_mail() by Max Howell
http://www.php.net/manual/en/ref.mail.php#72836
Works like a charm, but "iso-9959-1" is likely a typo. I guess "iso-889-1" was meant - though "utf-8" is arguably better anyway.


fontajos

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);
?>


php

Postfix under Mandrake 10.0 also objects to \\r\\n. The result is that every email is double-spaced, and all attachments break. (it was OK in 9.1).  My (short-term) fix is this:
$message = str_replace("\r",'',$message);
This discussion may be relevant:
http://www.phpdiscuss.com/article.php?id=60615&group=php.bugs


francesco piraneo g.

Please note that the 'sendmail_from' parameter is used also on php running under linux, not only under Windows as stated on the documentation.
Webmail services and some spam washer software kill messages without the "From" field properly set.
Try the following:
ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
mail($emailaddress, $emailsubject, $msg, $headers);
...as correctly reported by nielsvandenberge at hotmail dot com.
For further info: fpiraneo at gmail dot com


accius

One small error in nielsvan den berge's code:
ini_set(sendmail_from,$fromaddress) should be written ini_set("sendmail_from",$fromaddress) and ini_restore(sendmail_from) : ini_restore("sendmail_from")
Even with the "sendmail_from" set, SpamAssassin tags the message with NO_REAL_NAME, I didn't find out he solution yet


ben cooke

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.


say_ten

Nice example script, although please note that:
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
Should be:
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;


rob

New and Improved - well for gmail users at least. Their SMTP responds differently than other MTA"s. Make sure to enable the pop mail in the gmail account settings first
function authgMail($from, $namefrom, $to, $nameto, $subject, $message)
{
/*  your configuration here  */
$smtpServer = "tls://smtp.gmail.com"; //does not accept STARTTLS
$port = "465"; // try 587 if this fails
$timeout = "45"; //typical timeout. try 45 for slow servers
$username = "yous@gmail.com"; //your gmail account
$password = "y0u4p@55"; //the pass for your gmail
$localhost = $_SERVER['REMOTE_ADDR']; //requires a real ip
$newLine = "\r\n"; //var just for newlines

/*  you shouldn't need to mod anything else */
//connect to the host and port
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
echo $errstr." - ".$errno;
$smtpResponse = fgets($smtpConnect, 4096);
if(empty($smtpConnect))
{
  $output = "Failed to connect: $smtpResponse";
  echo $output;
  return $output;
}
else
{
  $logArray['connection'] = "Connected to: $smtpResponse";
  echo "connection accepted
".$smtpResponse."<p />Continuing<p />";
}
//you have to say HELO again after TLS is started
  fputs($smtpConnect, "HELO $localhost". $newLine);
  $smtpResponse = fgets($smtpConnect, 4096);
  $logArray['heloresponse2'] = "$smtpResponse";
 
//request for auth login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authrequest'] = "$smtpResponse";
//send the username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authusername'] = "$smtpResponse";
//send the password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authpassword'] = "$smtpResponse";
//email from
fputs($smtpConnect, "MAIL FROM: <$from>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailfromresponse'] = "$smtpResponse";
//email to
fputs($smtpConnect, "RCPT TO: <$to>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailtoresponse'] = "$smtpResponse";
//the email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data1response'] = "$smtpResponse";
//construct headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;
//observe the . after the newline, it signals the end of message
fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data2response'] = "$smtpResponse";
// say goodbye
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['quitresponse'] = "$smtpResponse";
$logArray['quitcode'] = substr($smtpResponse,0,3);
fclose($smtpConnect);
//a return value of 221 in $retVal["quitcode"] is a success
return($logArray);
}


chris

mail() opens a new connection for each email it sends out which causes some significant overhead if you're sending out many emails in one go.
You can avoid this by using sockets like Antony Male has done and then send as many emails as you like through the same connection.  It should be noted however that some MTA's will reject your emails after you've sent over a certain threshold on the same connection (about 10 would be normal) so it's worth disconnecting and reconnecting periodically.
I'm surprised nobody has drawn attention to PHPMailer (http://phpmailer.sourceforge.net) which makes this sort of stuff really easy.  Even better still is Swift Mailer by Chris Corbyn (http://www.swiftmailer.org) because it includes plugin support and it's tighter.
Another thing that's bitten me before is Magic Quotes! If it's turned on and you're sending attachments that seem to arrive corrupted it's more than likely because your attachments are full of backslashes.
Hope the links might be useful to some people :)


super david

Just to follow up on Nick Baicoianu's useful note below, one minor correction to make (it drove me insane for a while there until I noticed it):
This line:
<?php
$msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol;
?>
Should in fact read:
<?php
$headers .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol;
?>
The line should be declared as a header, not as part of the message content.


sevr

It is seems that quotes is needed in the header in charset param. Outlook can't define encoding without them.
$headers = "Content-Type: text/html; charset=\"windows-1251\"\r\n";
$headers .= "MIME-Version: 1.0 ";


nielsvandenberge

In the post I made about the send_mail() function at 28-Aug-2007 05:15 is a small problem.
the text:
<?php
 $headers .= 'MIME-Version: 1.0'.$eol.$eol;
?>
should be replaced by
<?php
 $headers .= 'MIME-Version: 1.0'.$eol;
?>
With a double "end of line" you close the header of a block so then the body should start. The Body also ends with two eol's
An e-mail is build up with some blocks, and those blocks can also contain blocks. Every block has a header where is defined what kind of block it is (content-Type). This content can be the texts and attachments for example.

The blocks are separated with a boundary, which is also defined in the header of a block (always starts with two dashes). After the header of a block you should put two "end of lines" (eol) and a boundary. The last block ends with a boundary plus two dashes (so it looks like "--BOUNDARY--") and 2 eol's
When a block contains other blocks (like we did with the HTML/Plain text part), the blocks should be separated by a different boundary then we used before.
So an email will look like:
Mail Header [define boundary "--123"]
2 eol
--123
header block 1 [define boundary "--456"]
2eol
   --456
   header block 1.1
2eol
   content block 1.1
2eol
   --456
   header block 1.2
2eol
   content block 1.2
2eol
   --456--
2eol
--123
header block 2
2eol
content block 2
2eol
--123--
2eol
Have fun with it


nick baicoianu

In response to jcwebb's excellent post regarding multipart/alternative and attachments: the code works great in sending attachments, but I got inconsistent results across different email clients (MS Outlook worked, but Thunderbird and mutt didn't) when displaying the HTML/plain text alternate portion.
To fix this, you need to define a new MIME boundary for the HTML/Plain text alternates section ONLY - this way you can "nest" the two together so the alternate works properly in all email clients.  
here's a modified version of the code for the message body only (see jcwebb's post for the entire message code)
<?
$msg = "";
# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: application/pdf; name=\"".$letter."\"".$eol;  // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$letter."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
# Setup for text OR html -
$msg .= "--".$mime_boundary.$eol;
$htmlalt_mime_boundary = $mime_boundary."_htmlalt"; //we must define a different MIME boundary for this section for the alternative to work properly in all email clients
$msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol;
# Text Version
$msg .= "--".$htmlalt_mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= "This is a multi-part message in MIME format.".$eol;
$msg .= "If you are reading this, please update your email-reading-software.".$eol;
$msg .= "+ + Text Only Email from Genius Jon + +".$eol.$eol;
# HTML Version
$msg .= "--".$htmlalt_mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= $body.$eol.$eol;
//close the html/plain text alternate portion
$msg .= "--".$htmlalt_mime_boundary."--".$eol.$eol;
# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol;
?>


anselm

In case you don't want to, or can't, configure sendmail for your server, a good alternative is esmtp - it's an smtp mailer with minimum configuration that can be used as a sendmail drop-in : http://esmtp.sourceforge.net/

07-apr-2004 01:36

If your system MTA is exim, you might find using it the following way gives you more control over the message that is sent. It uses batch SMTP rather than the hideous "-t" sendmail-like argument, and as a result allows the envelope and the headers to be specified seperately.
recipient, subject, body, [ [ [ headers ], sender ], helo]
bsmtp("recipient@address.com", "Subject", array("Line 1", "Line 2"), array(), "sender@address.com", "host.address.com);
OR
bsmtp(array("recipient1@address.com", "recipient2@address.com), "Subject", array("Line 1", "Line 2"), array(), "sender@addr$
<?php
function bsmtp($recipients, $subject,
$body, $headers = array(),
$sender= "<>",  $helo = "")
{
       $exim = "/usr/local/sbin/exim -bS";
       if ( $helo == "" )
       {
               $helo = $_SERVER["HTTP_HOST"];
       }
       if ( ! $headers )
       {
               if (is_array($recipients))
               {
                       $c="To: ";
                       foreach ($recipients as $r)
                       {
                               $toheader .= $c . $r;
                               $c = ", ";
                       }
               }
               else
               {
                       $toheader = "To: " . $recipients;
               }
               if ( ereg("@", $sender))
               {
                       $fromheader = "From: " . $sender;
               }
               else
               {
                       $fromheader = "From: <MAILER-DAEMON@" . $_SERVER["HTTP_HOST"] . ">";
               }
               $subj = "Subject: " . $subject;
               $headers = array($toheader, $fromheader, $subj);
       }
       $headers[] = "X-Mailer: Dave's better php mail function";
       print "<PRE>";
       $fd = popen($exim, "w");
       fputs($fd, "HELO " . $helo . "\n");
       fputs($fd, "MAIL FROM: " . $sender . "\n");
       if (is_array($recipients))
       {
               foreach ($recipients as $r)
               {
                       fputs($fd, "RCPT TO: " . $r . "\n");
               }
       }
       else
       {
               fputs($fd, "RCPT TO: " . $recipients . "\n");
       }
       fputs($fd, "DATA\n");
       foreach ( $headers as $h )
       {
               fputs($fd, $h . "\n");
       }
       fputs($fd, "\n");
       foreach ( $body as $b )
       {
               fputs($fd, $b . "\n");
       }
       fputs($fd, "\n.\nQUIT\n");
       sleep(1);
       pclose($fd);
}
}
?>


timo dot witte

if you wonder how to encode an subject in UTF-8 do it like this:
<?php
mail("timo.witte@kwick.de", "=?UTF-8?B?".base64_encode("also öhm äähh ühh puh ja die Sonderzeichen")."?=", "asbdasdasd bla blabla", $headers);
?>
=UTF-8?B?[Base64 encoded Subject]?=
The B stands for Base64 you could use Q instead of B and encode your UTF-8 string in 7 bit ASCII but base64 is simpler i think.
why encoding?
because you are not allowed to use 8-bit ASCII in mailheaders only 7-bit ASCII is allowed and pure utf-8 uses 8-bit ASCII characters.


metin savignano
If you want to use the mail() function under *nix and Windows alike, I recommend using the little fake sendmail utility available under http://glob.com.au/sendmail/ (bsd license).
I tried it and it works great for me. I can use the very same PHP code on both the Linux server as well as my Windows test machine. It supports auth smtp.
Instructions: Download fake sendmail, unzip it into a directory of your choice, customize the sendmail.ini to your smtp server, set the sendmail path in your php.ini, and you're done.


furrykef

If you use a regexp to validate an e-mail address, be sure that you actually use a correct regexp. In particular, there are more valid punctuation characters than you may think. All of these characters may appear to the left of the at-sign: ! # $ % & ' * + - / = ? ^ _ ` { | } ~
Don't believe me? Look at RFC 2822, which defines the current standard for e-mail addresses. ;)
There's no reason, other than laziness, to reject e-mail address that contain these characters to the left of the at-sign. You might think that nobody uses these characters, but people who write incorrect regexps are one reason why. Do your part to correct this situation. :)
Note in particular the plus sign. Many regexps reject addresses with the plus sign, but there are e-mail addresses that have them. In particular, gmail has a special feature called "plus addressing", so that if your username is "joeuser", you can use "joeuser+web at gmail dot com" and "joeuser+business at gmail dot com" as separate addresses, and the e-mail will be sorted depending on which address was used.
Even allowing all those punctuation characters isn't enough to fully satisfy RFC2822. For example, you can use quoted strings to allow spaces in e-mail addresses, such as "joe user" at somewhere dot com. But I wouldn't worry about such things too much, because they're too obscure; just make sure you get all the punctuation characters in there.


expertphp

If you try to set "From:" e-mail header value under Windows when it is already defined in php.ini "sendmail_from" value, this will doesn't work. If you still want to customize this value, then you must use another option like XPertMailer ( http://www.xpertmailer.com/ ) to send the e-mail directly to the client SMTP server or use a relay SMTP server with authentification option.

jo

If you have programmed headers do not adopt post-values unfiltered!!
Often used in scripts, and often abused by spam mailings:
$headers = "From: {$email}";
If somebody posts email="me@example.com
Bcc:someone1@example.com,someoneelse@example.com,..."
(with linebreak behind me@example.com)
You get following headers:
From: me@example.com
Bcc:someone1@example.com,someoneelse@example.com,...


roberto dot silva

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.
<?
include("Mail.php");
$recipients = "mail_to@domain.mail";
$headers["From"]    = "mail_from@domain.mail";
$headers["To"]      = "mail_to@domain.mail";
$headers["Subject"] = "Test message";
$body = "TEST MESSAGE!!!";
$params["host"] = "smtp.server";
$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 pear.php.net and install it, in my case, I needed to add the Socket.php to the PEAR library.


26-may-2005 11:18

If you are seeing unwanted line breaks preceded by exclamation marks ("!") in the emails you send with mail(), you may be having the same problem I had: exceeding the maximum line length (998 chars) specified in RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html).
You can get around this restriction by using base64 encoding: add a "Content-Transfer-Encoding: base64" header and encode the contents with
 $base64contents = rtrim(chunk_split(
   base64_encode($contents)));


martin dot felis

If using a chroot environment and you don't want to have a full mailer in it, mini-sendmail (can be found at http://www.acme.com/software/mini_sendmail/) is very useful. It is just a small binary that sends mails over your local mta over port 25.
Martin


pop

If sendmail on your linux server is configured with options:
sendmail -t -i
you may have problems sending mail if you put something like this in your header
<?
$headers .= "Return-Path: MyName <myname@myhost.com> /n";
?>
nstead use
<?
$headers .= "Reply-To: MyName <myname@myhost.com> /n";
?>


brett

I was having problems with all php emails showing up on my Exchange server as attachements instead of normal emails. I discovered that Exchange needs the MIME Version header. I simply added this to the beginning of my email headers:
$headers .= "MIME-Version: 1.0\r\n";
Now messages show up properly when they arrive at my Exchange server.


nielsvan den berge

I updated the function with help of some comments on this page and some research on the internet and this is the final result.
I tested it with MS Outlook, MS Outlook Express, Mozilla Thunderbird, Yahoo webmail, Hotmail, MS Exchange Webaccess and Horde (text-version) and they all gave the desired output with and without attachments.
Spamassassin also accepts this form of sending e-mails, when you use a clean e-mailaddress and body.
<?php
function send_mail($to, $body, $subject, $fromaddress, $fromname, $attachments=false)
{
 $eol="\r\n";
 $mime_boundary=md5(time());
 # Common Headers
 $headers .= "From: ".$fromname."<".$fromaddress.">".$eol;
 $headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
 $headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol;    // these two to set reply address
 $headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
 $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters
 # Boundry for marking the split & Multitype Headers
 $headers .= 'MIME-Version: 1.0'.$eol.$eol;
 $headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;
 # Open the first part of the mail
 $msg = "--".$mime_boundary.$eol;
 
 $htmlalt_mime_boundary = $mime_boundary."_htmlalt"; //we must define a different MIME boundary for this section
 # Setup for text OR html -
 $msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol.$eol;
 # Text Version
 $msg .= "--".$htmlalt_mime_boundary.$eol;
 $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
 $msg .= strip_tags(str_replace("
", "\n", substr($body, (strpos($body, "<body>")+6)))).$eol.$eol;
 # HTML Version
 $msg .= "--".$htmlalt_mime_boundary.$eol;
 $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
 $msg .= $body.$eol.$eol;
 //close the html/plain text alternate portion
 $msg .= "--".$htmlalt_mime_boundary."--".$eol.$eol;
 if ($attachments !== false)
 {
   for($i=0; $i < count($attachments); $i++)
   {
     if (is_file($attachments[$i]["file"]))
     {  
       # File for Attachment
       $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
       
       $handle=fopen($attachments[$i]["file"], 'rb');
       $f_contents=fread($handle, filesize($attachments[$i]["file"]));
       $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
       $f_type=filetype($attachments[$i]["file"]);
       fclose($handle);
       
       # Attachment
       $msg .= "--".$mime_boundary.$eol;
       $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;  // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
       $msg .= "Content-Transfer-Encoding: base64".$eol;
       $msg .= "Content-Description: ".$file_name.$eol;
       $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
       $msg .= $f_contents.$eol.$eol;
     }
   }
 }
 # Finished
 $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
 
 # SEND THE EMAIL
 ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
 $mail_sent = mail($to, $subject, $msg, $headers);
 
 ini_restore(sendmail_from);
 
 return $mail_sent;
}
?>


mark

i tried out 3 different scripts, and played with them for a few hours. Ugh.
Max Howell's mxcl mail function worked right off the bat - attachments, and body.  using RH + php 4.4.
thanks max!


pbglez

I think the easiest way to make correct attachments is checking The Official MIME Specification: http://www.hunnysoft.com/mime/  (Of course it isnt the only web page where you can find it ).
    I found there an example than truly helped me to make correct attachments:
Appendix A -- A Complex Multipart Example
  What follows is the outline of a complex multipart message.  This
  message contains five parts that are to be displayed serially:  two
  introductory plain text objects, an embedded multipart message, a
  text/enriched object, and a closing encapsulated text message in a
  non-ASCII character set.  The embedded multipart message itself
  contains two objects to be displayed in parallel, a picture and an
  audio fragment.
    MIME-Version: 1.0
    From: Nathaniel Borenstein <nsb@nsb.fv.com>
    To: Ned Freed <ned@innosoft.com>
    Date: Fri, 07 Oct 1994 16:15:05 -0700 (PDT)
    Subject: A multipart example
    Content-Type: multipart/mixed;
                  boundary=unique-boundary-1
    This is the preamble area of a multipart message.
    Mail readers that understand multipart format
    should ignore this preamble.
    If you are reading this text, you might want to
    consider changing to a mail reader that understands
    how to properly display multipart messages.
    --unique-boundary-1
      ... Some text appears here ...
    [Note that the blank between the boundary and the start
     of the text in this part means no header fields were
     given and this is text in the US-ASCII character set.
     It could have been done with explicit typing as in the
     next part.]
    --unique-boundary-1
    Content-type: text/plain; charset=US-ASCII
    This could have been part of the previous part, but
    illustrates explicit versus implicit typing of body
    parts.
    --unique-boundary-1
    Content-Type: multipart/parallel; boundary=unique-boundary-2
    --unique-boundary-2
    Content-Type: audio/basic
    Content-Transfer-Encoding: base64
      ... base64-encoded 8000 Hz single-channel
          mu-law-format audio data goes here ...
    --unique-boundary-2
    Content-Type: image/jpeg
    Content-Transfer-Encoding: base64
      ... base64-encoded image data goes here ...
    --unique-boundary-2--
    --unique-boundary-1
    Content-type: text/enriched
    This is <bold><italic>enriched.</italic></bold>
    <smaller>as defined in RFC 1896</smaller>
    Isn't it
    <bigger><bigger>cool?</bigger></bigger>
    --unique-boundary-1
    Content-Type: message/rfc822
    From: (mailbox in US-ASCII)
    To: (address in US-ASCII)
    Subject: (subject in US-ASCII)
    Content-Type: Text/plain; charset=ISO-8859-1
    Content-Transfer-Encoding: Quoted-printable
      ... Additional text in ISO-8859-1 goes here ...
    --unique-boundary-1--


geoff montreal

i strongly feel that internet site developers should exclusively use UTF-8 text encoding / character setting over ISO-8859-1... UTF-8 is universal and will display all characters as they were meant to be displayed, whereas ISO-8859-1 is prone to garbled text.
<?php
$message .= "Content-Type: text/plain; charset=UTF-8\n";
?>
~ and/or ~
<?php
$message .= "Content-Type: text/html; charset=UTF-8\n";
?>
note:  above code for *nix servers.


andrew w

I spent weeks trying to work out why PHP couldnt send mail through Exim (called locally) when for all other purposes Exim worked fine.  Here, after hours of work is the answer and I hope it saves someone else some time:
PHP by default calls sendmail/exim/whatever with the options -t & -i
-i is causing Exim to sit there waiting for more input, not detecting the end of the message.  You need to tell it not to use -i by manually specifying the arguments you DO want on sendmail_path like this:
sendmail_path = /path/to/exim -t


aweather88

I spent hours searching the web trying to figure out why I was getting a "WARNING: mail(): SMTP server response: 501 5.5.4 Invalid Address " every time I was using the mail() function on my server (Win2K3,IIS 6.0,PHP4.4.1).  I knew everything was setup properly for SMTP based on other non IIS 6.0 configurations.
Turns out that the IIS 6.0 SMTP service does not like formatting of the "From" field in mail headers.  For instance:
<?PHP
  //This line DOES NOT send  mail message correctly
  $headers .= "From: \"".$fromname."\" <".$fromaddress.">\n";
?>
However this works:
<?PHP
  //This line sends mail message correctly
  $headers .= "From: \"".$fromaddress."\"\n";
?>
The fix is in Microsoft Article ID 291828 ( http://support.microsoft.com/?id=291828 ).  Even though the "bug" workaround is for IIS 6.0 on Exchange 2003 communicating with a UNIX server, THIS SOLVES THE PROBLEM.  Just skip down to the last section for Exchange 2003 and follow the instructions to modify the IIS 6 MetaBase with the MetaBase Explorer found in the IIS 6 Resource Kit.


eflores

I need help. When I send the email the attachments and the multiparts are displayed as text. What am I doing wrong? I have tried the double eols and still have no clue. Here is my code.
<?php
$txt="The report contains locations on the ground for at least 16 weeks and no more than 17 weeks. A summary of last 3 weeks productivity and its average is included. Size".strlen($data);
// Generate a boundary string
$mime_boundary = "<<<--==+X[".md5(time())."]\r\n\r\n";

 // Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\r\n\r\n".
           "--".$mime_boundary."\r\n".
           "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n".
           "Content-Transfer-Encoding: 7bit\r\n".
           $txt."\r\n\r\n".
"--".$mime_boundary."\r\n";
// Base64 encode the file data
$data="Dummy Info";
$data = chunk_split(base64_encode($data));
 $fileatt_type="application/vnd.ms-excel;";
 $fileatt_name="startupLocations.xls";
// Add file attachment to the message
$message .= "Content-Type: ".$fileatt_type."\r\n" .
            " name=\"".$fileatt_name."\"\r\n" .
            "Content-Transfer-Encoding: base64\r\n" .
            "Content-Disposition: attachment;\r\n" .
            " filename=\"".$fileatt_name."\"\r\n\r\n" .
            $data."\r\n" .
            "--".$mime_boundary."\r\n";
// Add the headers for a file attachment
$reportName='Comissions';
unset($sendTo);
$sql = "SELECT * FROM distributionlist left join autoemailtabs
on distributionlist.reporttabid=autoemailtabs.id
WHERE tabname='".$reportName."';";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$sendTo[] = $row['email'];
}
for($j=0;$j<sizeof($sendTo);$j++){
$headers = "From:eaflores@sterlingandbaxter.com\r\n".
"To:".$sendTo[$j]."\r\n".
"MIME-Version: 1.0\r\n" .
            "Content-Type: multipart/mixed;\r\n".
            "boundary=\"".$mime_boundary."\"\r\n";

mail($sendTo[$j],' STS Comissions ',$message,$headers);
}//ednFor
//END SEND EMAIL
?>


admin

I just spent a few hours working on getting a simple html formatted email to work on outlook. This is the end result:
<?php
$body="<em>HTML</em> formatted <strong>Message</strong";

$headers = "From: info@example.com \r\n";
$headers.= "Content-Type: text/html; charset=ISO-8859-1 ";
$headers .= "MIME-Version: 1.0 ";
/*notice there aren't any \r\n after the second two header additions. This is what made this version work correctly*/
mail("john@example.com", "An HTML Message", $body, $headers);
?>


webbieatvlaanderendashflandersdotcom

I have the problem that, using EasyPHP 1.8, I constantly get the error 530, meaning I need to authenticate.
Yet, in my php.ini I have changed the [mail function] to my own ISP's SMTP server and sendmail_from to my own emailaddress.
yet when I reboot, in my php.ini file everything is as I left it, while phpinfo() still tells me my SMTP serve is set to localhost.
Has anyone got any idea where I might have gone wrong?


josephcmiller2

I have been using the function mymail() provided by Antony Male (below) to send mail on my server, but with a couple of modifications.  First, I needed to enable AUTH LOGIN in order to use my smtp server from my ISP.  Second, his mymail() function allows for a $from to be used, but the function does not accept any such parameter.  I have addressed the latter issue by parsing the headers to obtain the From: address.  If this is not provided, failed mail will not be returned properly to the sender.
// modified to provide authenticated logins
function mymail($to,$subject,$message,$headers)
{
 // set as global variable
 global $GLOBAL;
 
 // get From address
 if ( preg_match("/From:.*?[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+.*/", $headers, $froms) ) {
  preg_match("/[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+/", $froms[0], $fromarr);
  $from = $fromarr[0];
 }
 // Open an SMTP connection
 $cp = fsockopen ($GLOBAL["SMTP_SERVER"], $GLOBAL["SMTP_PORT"], &$errno, &$errstr, 1);
 if (!$cp)
  return "Failed to even make a connection";
 $res=fgets($cp,256);
 if(substr($res,0,3) != "220") return "Failed to connect";
 // Say hello...
 fputs($cp, "HELO ".$GLOBAL["SMTP_SERVER"]."\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "250") return "Failed to Introduce";
 
 // perform authentication
 fputs($cp, "auth login\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "334") return "Failed to Initiate Authentication";
 
 fputs($cp, base64_encode($GLOBAL["SMTP_USERNAME"])."\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "334") return "Failed to Provide Username for Authentication";
 
 fputs($cp, base64_encode($GLOBAL["SMTP_PASSWORD"])."\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "235") return "Failed to Authenticate";
 // Mail from...
 fputs($cp, "MAIL FROM: <$from>\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "250") return "MAIL FROM failed";
 // Rcpt to...
 fputs($cp, "RCPT TO: <$to>\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "250") return "RCPT TO failed";
 // Data...
 fputs($cp, "DATA\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "354") return "DATA failed";
 // Send To:, From:, Subject:, other headers, blank line, message, and finish
 // with a period on its own line (for end of message)
 fputs($cp, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "250") return "Message Body Failed";
 // ...And time to quit...
 fputs($cp,"QUIT\r\n");
 $res=fgets($cp,256);
 if(substr($res,0,3) != "221") return "QUIT failed";
 return true;
}


spinningvertex

I found the mail validator http://www.apps.ietf.org/msglint.html  to be very usefull.

accius

I found out the solution for my problem with spamassassin. The sender name and address should be separed with space :
$headers .= "From: ".$fromname." <".$fromaddress.">".$eol;
or
$from = $fromname." <".$fromaddress.">";
ini_set("sendmail_from",$from)


max howell

I find this a useful function, and it's a lot easier to read and edit than the proceeding set. Many thanks to the proceeding set though, since they taught me how to do it!
<?php
function mxcl_mail( $subject, $message )
{
ob_start();
print_r( $GLOBALS );
$teh_globals = chunk_split( base64_encode( ob_get_clean() ) ); // base 64 encode

$date = date( 'r' );
$phpversion = phpversion();
$boundary = md5( time() );
$filename = '$GLOBALS.txt';

$headers = <<<END
From: $_SERVER[PHP_SELF] <php@$_SERVER[SERVER_NAME]>
Date: $date
X-Mailer: PHP v$phpversion
MIME-Version: 1.0
Content-Type: multipart/related; boundary="$boundary"
END;
$message = <<<END
--$boundary
Content-Type: text/plain; charset="iso-9959-1"
Content-Transfer-Encoding: 7bit
$message
--$boundary
Content-Type: octet-stream; name="$filename"
Content-Disposition: attachment; filename="$filename"
Content-Transfer-Encoding: base64
$teh_globals
--$boundary--
END;
mail( 'webmaster@example.com', $subject, $message, $headers );
}
?>


nielsvandenberge

I edited the code of genius Jon (thank you!) a bit and made an easy function to send multiple attachments with one e-mail. I stripped the HTML tags for the text-version, but haven't tested that.
The attachments variable of the function is a 2-dimensional array which should contain the keys "file" and "content_type".
I tested it with MS Outlook.
<?php
function send_mail($emailaddress, $fromaddress, $emailsubject, $body, $attachments=false)
{
 $eol="\r\n";
 $mime_boundary=md5(time());
 
 # Common Headers
 $headers .= 'From: MyName<'.$fromaddress.'>'.$eol;
 $headers .= 'Reply-To: MyName<'.$fromaddress.'>'.$eol;
 $headers .= 'Return-Path: MyName<'.$fromaddress.'>'.$eol;    // these two to set reply address
 $headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
 $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters
 # Boundry for marking the split & Multitype Headers
 $headers .= 'MIME-Version: 1.0'.$eol;
 $headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
 $msg = "";      
 
 if ($attachments !== false)
 {
   for($i=0; $i < count($attachments); $i++)
   {
     if (is_file($attachments[$i]["file"]))
     {  
       # File for Attachment
       $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
       
       $handle=fopen($attachments[$i]["file"], 'rb');
       $f_contents=fread($handle, filesize($attachments[$i]["file"]));
       $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
       fclose($handle);
       
       # Attachment
       $msg .= "--".$mime_boundary.$eol;
       $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;
       $msg .= "Content-Transfer-Encoding: base64".$eol;
       $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
       $msg .= $f_contents.$eol.$eol;
       
     }
   }
 }
 
 # Setup for text OR html
 $msg .= "Content-Type: multipart/alternative".$eol;
 
 # Text Version
 $msg .= "--".$mime_boundary.$eol;
 $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol;
 $msg .= strip_tags(str_replace("
", "\n", $body)).$eol.$eol;
 
 # HTML Version
 $msg .= "--".$mime_boundary.$eol;
 $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol;
 $msg .= $body.$eol.$eol;
 
 # Finished
 $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
   
 # SEND THE EMAIL
 ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
 mail($emailaddress, $emailsubject, $msg, $headers);
 ini_restore(sendmail_from);
 echo "mail send";
}
 
# To Email Address
$emailaddress="to@address.com";
# From Email Address
$fromaddress = "from@address.com";
# Message Subject
$emailsubject="This is a test mail with some attachments";
# Use relative paths to the attachments
$attachments = Array(
 Array("file"=>"../../test.doc", "content_type"=>"application/msword"),
 Array("file"=>"../../123.pdf", "content_type"=>"application/pdf")
);
# Message Body
$body="This is a message with <b>".count($attachments)."</b> attachments and maybe some <i>HTML</i>!";
send_mail($emailaddress, $fromaddress, $emailsubject, $body, $attachments);
?>


stevenlim

How to detect a bounce email
1. make sure the email you send out have the header
"Return-Path: detect-bounce@yourdomain.com\r\n",
&
"Return-Receipt-To: bounce@yourdomain.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 (www.Edinburgh-Consulting.com)


jdephix

How to add multiple attachment to an email:
An email can be split into many parts separated by a boundary followed by a Content-Type and a Content-Disposition.
The boundary is initialized as follows:
<?php
$boundary = '-----=' . md5( uniqid ( rand() ) );
?>
You can attach a Word document if you specify:
<?php
$message .= "Content-Type: application/msword; name=\"my attachment\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment; filename=\"$theFile\"\n\n";
?>
When adding a file you must open it and read it with fopen and add the content to the message:
<?php
$path = "whatever the path to the file is";
$fp = fopen($path, 'r');
do //we loop until there is no data left
{
       $data = fread($fp, 8192);
       if (strlen($data) == 0) break;
       $content .= $data;
     } while (true);
$content_encode = chunk_split(base64_encode($content));
$message .= $content_encode . "\n";
$message .= "--" . $boundary . "\n";
?>
Add the needed headers and send!
<?php
$headers  = "From: \"Me\"<me@here.com>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
mail('myAddress@hotmail.com', 'Email with attachment from PHP', $message, $headers);
?>
Finally, if you add an image and want it displayed in your email, change the Content-Type from attachment to inline:
<?php
$message .= "Content-Disposition: inline; filename=\"$theFile\"\n\n";
?>
Enjoy!


peekepichotmailcom

Hi all, i recently update my server to another more powerful and since some pop3 servers like "gmail" display my emails like an HTML code :(
After one night, i've found the bug and some info on internet :
"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".
I replace my CRLF separator by LF onyl and all my users received a correct email. PeekEpic.


geoff in montreal

Here is a PHP Mail Multipart/Alternative (Plain Text and HTML) code for *nix servers (Unix Like Servers)... if you are hosted on a windows server, simply replace all "\n" or "\n\n" in the below code to "\r\n" or "\r\n\r\n" respectively.
This code is for anyone who has already written an HTML page for their PHP mail... there are several PHP > HTML free translators on the internet.  You may use one of them to translate your HTML code to PHP to insert into the following code.  All there needs to change is to place a backslash before any quotations (EX: ... confirm that \"Our Company\" has ...), and to end each line with a newline character (EX: \n )...
This code method has been successfully tested with Apple Mail, Microsoft Outlook, G-Mail, and Yahoo Mail.  I hope this helps out anyone that is writing a multipart/alternative PHP mailer script.
<?php
# -=-=-=- PHP FORM VARIABLES (add as many as you would like)
$name = $_POST["name"];
$email = $_POST["email"];
$invoicetotal = $_POST["invoicetotal"];
# -=-=-=- MIME BOUNDARY
$mime_boundary = "----Your_Company_Name----".md5(time());
# -=-=-=- MAIL HEADERS
$to = "$email";
$subject = "This text will display in the email's Subject Field";
$headers = "From: Our Company <company@ourcompany.com>\n";
$headers .= "Reply-To: Our Company <company@ourcompany.com>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
# -=-=-=- TEXT EMAIL PART
$message = "--$mime_boundary\n";
$message .= "Content-Type: text/plain; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "$name:\n\n";
$message .= "This email is to confirm that \"Our Company\" has received your order.\n";
$message .= "Please send payment of $invoicetotal to our company address.\n\n";
$message .= "Thank You.\n\n";
# -=-=-=- HTML EMAIL PART

$message .= "--$mime_boundary\n";
$message .= "Content-Type: text/html; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "<html>\n";
$message .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif; font-size:14px; color:#666666;\">\n";
$message .= "$name:
\n";
$message .= "
\n";
$message .= "This email is to confirm that \"Our Company\" has received your order.
\n";
$message .= "Please send payment of $invoicetotal to our company address.
\n\n";
$message .= "
\n";
$message .= "Thank You.
\n\n";
$message .= "</body>\n";
$message .= "</html>\n";
# -=-=-=- FINAL BOUNDARY
$message .= "--$mime_boundary--\n\n";
# -=-=-=- SEND MAIL
$mail_sent = @mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
?>


rob

Having beaten my head against an MCSE for several days over my need for a mail form and his need for "heightened security for IIS" I finally managed to get a working authentication model for Exchange 2003. (note: this will ONLY relay mail to actual users of the Exchange server. i.e. registered email address)
<?
function authMail($from, $namefrom, $to, $nameto, $subject, $message)
{
/*  your configuration here  */
$smtpServer = "mail.yourdomain.com"; //ip accepted as well
$port = "25"; // should be 25 by default
$timeout = "30"; //typical timeout. try 45 for slow servers
$username = "webform"; //the login for your smtp
$password = "passhere"; //the pass for your smtp
$localhost = "127.0.0.1"; //this seems to work always
$newLine = "\r\n"; //var just for nelines in MS
$secure = 0; //change to 1 if you need a secure connect
 
/*  you shouldn't need to mod anything else */
//connect to the host and port
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 4096);
if(empty($smtpConnect))
{
  $output = "Failed to connect: $smtpResponse";
  return $output;
}
else
{
  $logArray['connection'] = "Connected to: $smtpResponse";
}
//say HELO to our little friend
fputs($smtpConnect, "HELO $localhost". $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['heloresponse'] = "$smtpResponse";
//start a tls session if needed
if($secure)
{
  fputs($smtpConnect, "STARTTLS". $newLine);
  $smtpResponse = fgets($smtpConnect, 4096);
  $logArray['tlsresponse'] = "$smtpResponse";
  //you have to say HELO again after TLS is started
  fputs($smtpConnect, "HELO $localhost". $newLine);
  $smtpResponse = fgets($smtpConnect, 4096);
  $logArray['heloresponse2'] = "$smtpResponse";
}
//request for auth login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authrequest'] = "$smtpResponse";
//send the username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authusername'] = "$smtpResponse";
//send the password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authpassword'] = "$smtpResponse";
//email from
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailfromresponse'] = "$smtpResponse";
//email to
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailtoresponse'] = "$smtpResponse";
//the email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data1response'] = "$smtpResponse";
//construct headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;
//observe the . after the newline, it signals the end of message
fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data2response'] = "$smtpResponse";
// say goodbye
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['quitresponse'] = "$smtpResponse";
$logArray['quitcode'] = substr($smtpResponse,0,3);
fclose($smtpConnect);
//a return value of 221 in $retVal["quitcode"] is a success
return($logArray);
}
?>
Obviously this function can be expanded upon, and adding attachments should be no real issue based on code found on this page. For me the authentication was the goal; while I had seen many scripts offering it, none seemed to work. I hope this helps someone out there defeat their evil MCSE counterpart


judas dot iscariote

For those of you worried about Mail Injection .. Zend_Mail provides protection against this trick.
http://framework.zend.com/manual/zend.mail.html


lawcd

For those of you with the exim, if its not sending mail with the -i option and you cant easily change this, you might want to check out the imap_mail() function which works almost exactly the same and doesnt use exim, most web hosts provide this. If you using your own server then php needs to be compiled with imap libraries etc.
See http://uk2.php.net/manual/en/function.imap-mail.php


josh

For anyone having problems with attached files coming through garbled, make sure you have magic_quotes_runtime set to Off in your php.ini - it adds funky escape chars to your attached data and garbles the attachment.
This was giving me all kinds of grief.


expertphp

For all those having problems sending messages to INBOX (spam-free messages)
i recommend using FromHost() function from XPM2's SMTP class.
With this function you can set the name of the host that is sending the message.
Pay very much attention when using this function, because i recommend the IP address of the host
to reflect the MX zone declared for it, and the IP address of the mail sender.
A simple example of how to use for sending an e-mail directly to the client:
<?php
$hostname = 'maildomain.net';
// path to smtp.php file from XPM2 package for inclusion
require_once '/path/smtp.php';
$mail = new SMTP;
$mail->Delivery('client');
$mail->From('me@'.$hostname, 'My name');
$mail->FromHost($hostname, $havemx);
if(!$havemx) die("The hostname: '".$hostname."' doesn't have a valid MX zone!");
$mail->AddTo('client@destination.net');
$mail->Text('It is simple to use XPM2');
$sent = $mail->Send('Hello World!');
echo $sent ? 'Success.' : $mail->result;
?>
This is one of the most reliable anti-spam/bulk mail techniques.
For more details visit: http://xpertmailer.sourceforge.net/DOCUMENTATION/


jcwebb

Corrupted Attachments ???
I spent many hours with corrupted attachments (of all types of files) - The answer: a blank line is needed after $msg.=$file \r\n \r\n [incredible but true].
Heres some useful code for sending an attachment, and display html OR text depending on the users email-reader.
i work with many different systems, so...
<?php # Is the OS Windows or Mac or Linux
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
 $eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
 $eol="\r";
} else {
 $eol="\n";
} ?>
<?php
# File for Attachment
$f_name="../../letters/".$letter;    // use relative path OR ELSE big headaches. $letter is my file for attaching.
$handle=fopen($f_name, 'rb');
$f_contents=fread($handle, filesize($f_name));
$f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
$f_type=filetype($f_name);
fclose($handle);
# To Email Address
$emailaddress="him@her.com";
# Message Subject
$emailsubject="Heres An Email with a PDF".date("Y/m/d H:i:s");
# Message Body
ob_start();
 require("emailbody.php");     // i made a simple & pretty page for showing in the email
$body=ob_get_contents(); ob_end_clean();
# Common Headers
$headers .= 'From: Jonny <jon@genius.com>'.$eol;
$headers .= 'Reply-To: Jonny <jon@genius.com>'.$eol;
$headers .= 'Return-Path: Jonny <jon@genius.com>'.$eol;     // these two to set reply address
$headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol;           // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
$msg = "";
# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: application/pdf; name=\"".$letter."\"".$eol;   // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$letter."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
# Setup for text OR html
$msg .= "Content-Type: multipart/alternative".$eol;
# Text Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= "This is a multi-part message in MIME format.".$eol;
$msg .= "If you are reading this, please update your email-reading-software.".$eol;
$msg .= "+ + Text Only Email from Genius Jon + +".$eol.$eol;
# HTML Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= $body.$eol.$eol;
# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol;   // finish with two eol's for better security. see Injection.
# SEND THE EMAIL
ini_set(sendmail_from,'from@me.com');  // the INI lines are to force the From Address to be used !
 mail($emailaddress, $emailsubject, $msg, $headers);
ini_restore(sendmail_from);
?>
I hope this helps.
Jon Webb [Madrid&London]


furrykef

By the way, also read RFC 3696 and its errata. These define rules for e-mail addresses in more plain language.

contact

Brian, in your script text simply add a "\n" to the end of each line of text you want separated.  Add two "\n" for a space break between lines.  For example:
$message .= "First Name: $firstname\n";
$message .= "Last name: $lastname\n";
will send each of these to your email on separate lines.


wtmusic

Beware of Mac "line feeds" (\r) in long text strings in the body of a message--may cause Sendmail to insert exclamation points after every 256 chars

tinus

as to fred's posting, I had to change the code a bit:
-add a hashbang
-add "-t -i " to the sendmail call
great idea though.
#!/usr/bin/php
<?php
      $tmpfile = "/tmp/" . uniqid('') . ".mail";
      $fp = fopen($tmpfile,"w");
      fwrite($fp,"x-wls-cc-filter: On\n");
      while($line = fgets(STDIN))
      {
              $line = ereg_replace("^bcc:","x-wlsspam-bcc:",$line);
              $line = ereg_replace("^cc:","x-wlsspam-cc:",$line);
              fwrite($fp,$line);
      }
      fclose($fp);
      $cmd = '/usr/sbin/sendmail -t -i ';
      for($i = 1 ; $i < $argc; $i++)
      {
              $cmd .= $argv[$i];
              $cmd .= ' ';
      }
      $cmd .= "<$tmpfile";
      system($cmd);
?>


12-apr-2002 04:35

As noted above sendmail_from is only used on MS Windows, to change the default sender on unix you must add -f to sendmail_path. For example in a <VirtualHost> directive:
php_admin_value sendmail_path "/usr/sbin/sendmail -t -i -f webmaster@example.com"
would set the default return-path for mail from that virtual host.


webmaster

As mentioned earlier, for Windows users there is a fake sendmail option. A bit more detailed description how to do this is:
If you have a test server in use running Windows and some kind of WAMP combo (XXAMP, WAMP Server, etc) then you'll notice that the PHP sendmail command (mail()) does not work. Windows simply does not provide the sendmail statement ...
There is a simple trick to get this to work though;
1) Download (or use the attached file) sendmail.zip from http://glob.com.au/sendmail/
2) Unzip this in a folder on your c: drive (preferably use a simple path, for example c:\wamp\sendmail -- long filenames could cause problems)
3) Edit your PHP.INI file (note: WAMP users should access their php.ini file from the WAMP menu). Go to the [mail function] section and modify it as such:
[mail function]
; For Win32 only.
;SMTP =
; For Win32 only.
;sendmail_from =
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"
; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_paramaters =
.. and save the changes.
4) Open the sendmail.ini and modify the settings to:
[sendmail]
; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory.  (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.
smtp_server=mail.yourdomain.com
; smtp port (normally 25)
smtp_port=25
; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify
default_domain=yourdomain.com
; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging
; error_logfile=sendmail_error.log
; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging
; debug_logfile=sendmail_debug.log
; if your smtp server requires authentication, modify the following two lines
;auth_username=
;auth_password=
; if your smtp server uses pop3 before smtp authentication, modify the
; following three lines
pop3_server=mail.yourdomain.com
pop3_username=you@yourdomain.com
pop3_password=mysecretpassword
; to force the sender to always be the following email address, uncomment and
; populate with a valid email address.  this will only affect the "MAIL FROM"
; command, it won't modify the "From: " header of the message content
force_sender=you@yourdomain.com
; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting.  you can manually set the ehlo/helo name if required
hostname=
The optional error and debug logging is recommended when trying this the first time, so you have a clue what goes wrong in case it doesn't work.
Force_sender is also optional, but recommended to avoid confusion on the server end.
Obviously mail.yourdomain.com, you@yourdomain.com, and mysecretpassword should be the relevant info for your SMTP server.
Now restart the WAMP services (mainly Apache so PHP re-reads it's config).
Now you're good to go and use the PHP mail() statement as if you're a Unix user ...


fnjordy

Another example of sending a utf-8 HTML mail:
$to = 'bob@barnyard.com';
$subject = 'Wakeup bob!';
$message = '<b>yo</b>, whassup?';
$headers = "From: server@barnyard.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);


mail

@tudor:
Take a look at this class:
http://www.phpguru.org/static/mime.mail.html
<!-- snip from the description
A class for sending mime based email. It can send:
- HTML Email
- HTML Email with embedded images
- HTML Email with attachments
- HTML Email with embedded images and attachments
- Text email
- Text email with attachments
snap -->
This may help you with your problem
Regards,
Andre


f dot touchard

***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
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;
}


mail

<?php
function send_mail($MailTo = "", $SenderName = "Sender", $SenderMail = "no@reply.error", $Subject = "", $Mailcontent = "no.file", $Attachment = "no.file", $Servername = "PHPMAILSERVER", $nohtml  = "[ This message should be viewed in HTML. This is a degraded version! ]"){
   if(strtoupper(substr(PHP_OS,0,3)=='WIN')){
     $eol="\r\n";
     $sol="\n";
   }elseif(strtoupper(substr(PHP_OS,0,3)=='MAC')){
     $eol="\r";
   }else{
     $eol="\n";
   }
   if(!isset($sol)){
       $sol = $eol;
   }
   $Momentn = mktime().".".md5(rand(1000,9999));
   $f_name       = $Attachment;
   $handle       = fopen($f_name, 'rb');
   $f_contents   = @fread($handle, filesize($f_name));
   $f_contents   = @base64_encode($f_contents);
   if($handle){
       $sendfile = true;
       if(ini_get('mime_magic.debug')){
           $Bestype = @mime_content_type($Attachment);    
       }else{
           $Bestype = 'application/octet-stream';
       }
       if(!$Bestype){
           $Bestype = 'application/octet-stream';
       }
       $file_realname = explode("/", $Attachment);
       $file_realname = $file_realname[count($file_realname)-1];
       $file_realname = explode("\\", $file_realname);
       $file_realname = $file_realname[count($file_realname)-1];
   }
   @fclose($handle);
   $Mailcontentstri  = explode($sol, $Mailcontent);
   $Mailcontentstrip = strip_tags($Mailcontentstri[0]);
   
   if(@file_exists($Mailcontentstrip)){
       ob_start();
       if(require($Mailcontent)){  
           $body  = ob_get_contents();
       }
       ob_end_clean();
   }else{
       if(count($Mailcontentstri) < 2){
           $body  = "Error loading file!";
           $error = true;
       }else{
           $body  = $Mailcontent;    
       }
   }
               
   $Textmsg = eregi_replace("<br(.{0,2})>", $eol, $body);
   $Textmsg = eregi_replace("", $eol, $Textmsg);
   $Textmsg = strip_tags($Textmsg);
   $Textmsg = $nohtml.$eol.$eol.$Textmsg;
   $headers      .= 'To: '.$MailTo.' <'.$MailTo.'>'.$eol;
   $headers      .= 'From: '.$SenderName.' <'.$SenderMail.'>'.$eol;
   $headers      .= "Message-ID: <".$Momentn."@".$Servername.">".$eol;
   $headers      .= 'Date: '.date("r").$eol;
   $headers      .= 'Sender-IP: '.$_SERVER["REMOTE_ADDR"].$eol;
   $headers      .= 'X-Mailser: iPublications Adv.PHP Mailer 1.6'.$eol;
   $headers      .= 'MIME-Version: 1.0'.$eol;
   $bndp          = md5(time()).rand(1000,9999);
   $headers      .= "Content-Type: multipart/mixed; $eol       boundary=\"".$bndp."\"".$eol.$eol;
   $msg           = "This is a multi-part message in MIME format.".$eol.$eol;
   $msg          .= "--".$bndp.$eol;
   $bnd           = md5(time()).rand(1000,9999);
   $msg          .= "Content-Type: multipart/alternative; $eol       boundary=\"".$bnd."\"".$eol.$eol;
   $msg          .= "--".$bnd.$eol;
   $msg          .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
   $msg          .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
   $msg          .= $Textmsg.$eol;
   $msg          .= "--".$bnd.$eol;
   $msg          .= "Content-Type: text/html; charset=iso-8859-1".$eol;
   $msg          .= "Content-Transfer-Encoding: 8-bit".$eol.$eol;
   $msg          .= $body.$eol;
   $msg          .= "--".$bnd."--".$eol.$eol;
   if(isset($sendfile)){
       $msg          .= "--".$bndp.$eol;
       $msg          .= "Content-Type: $Bestype; name=\"".$file_realname."\"".$eol;
       $msg          .= "Content-Transfer-Encoding: base64".$eol;
       $msg          .= "Content-Disposition: attachment;".$eol;
       $msg          .= "       filename=\"".$file_realname."\"".$eol.$eol;
       $f_contents    = chunk_split($f_contents);
       $msg          .= $f_contents.$eol;
   }
   $msg          .= "--".$bndp."--";
   if(!isset($error)){
       if(@mail($MailTo, $Subject, $msg, $headers)){
           return true;  
       }else{
           return false;
       }
   }else{
       return false;
   }
}
?>


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker