You are on page 1of 51

Downloads

Documentation
Get Involved
Help
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
PHP: mail - Manual http://php.net/manual/en/function.mail.php
1 of 51 6/17/2014 2:07 PM
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
g p
Previous man page
g n
Next man page
G
Scroll to bottom
g g
PHP: mail - Manual http://php.net/manual/en/function.mail.php
2 of 51 6/17/2014 2:07 PM
Scroll to top
g h
Goto homepage
g s
Goto search
(current page)
/
Focus search box
Mailparse
ezmlm_hash
PHP Manual
Function Reference
Mail Related Extensions
Mail
Mail Functions
Change language:
Edit Report a Bug
mail
(PHP 4, PHP 5)
mail Send mail
Description
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string
$additional_parameters ]] )
Sends an email.
Parameters
to
Receiver, or receivers of the mail.
The formatting of this string must comply with RFC 2822. Some examples are:
user@example.com
user@example.com, anotheruser@example.com
User <user@example.com>
User <user@example.com>, Another User <anotheruser@example.com>
subject
Subject of the email to be sent.
Caution
PHP: mail - Manual http://php.net/manual/en/function.mail.php
3 of 51 6/17/2014 2:07 PM
Subject must satisfy RFC 2047.
message
Message to be sent.
Each line should be separated with a CRLF (\r\n). Lines should not be larger than 70 characters.
Caution
(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found on the start
of a line, it is removed. To counter-act this, replace these occurrences with a double dot.
<?php
$text = str_replace("\n.", "\n..", $text);
?>
additional_headers (optional)
String to be inserted at the end of the email header.
This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be
separated with a CRLF (\r\n). If outside data are used to compose this header, the data should be
sanitized so that no unwanted headers could be injected.
Note:
When sending mail, the mail must contain a From header. This can be set with the
additional_headers parameter, or a default can be set in php.ini.
Failing to do this will result in an error message similar to Warning: mail():
"sendmail_from" not set in php.ini or custom "From:" header missing. The From
header sets also Return-Path under Windows.
Note:
If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents
(most notably qmail) 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.
additional_parameters (optional)
The additional_parameters parameter can be used to pass additional flags as command line
options to the program configured to be used when sending mail, as defined by the sendmail_path
configuration setting. For example, this can be used to set the envelope sender address when using
sendmail with the -f sendmail option.
This parameter is escaped by escapeshellcmd() internally to prevent command execution.
escapeshellcmd() prevents command execution, but allows to add addtional parameters. For
security reasons, it is recommended for the user to sanitize this parameter to avoid adding unwanted
parameters to the shell command.
Since escapeshellcmd() is applied automatically, some characters that are allowed as email
addresses by internet RFCs cannot be used. mail() can not allow such characters, so in programs
PHP: mail - Manual http://php.net/manual/en/function.mail.php
4 of 51 6/17/2014 2:07 PM
where the use of such characters is required, alternative means of sending emails (such as using a
framework or a library) is recommended.
The user that the webserver runs as should be added as a trusted user to the sendmail configuration
to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is
set using this method. For sendmail users, this file is /etc/mail/trusted-users.
Return Values
Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail
will actually reach the intended destination.
Changelog
Version Description
4.3.0
(Windows
only)
All custom headers (like From, Cc, Bcc and Date) are supported, and are not
case-sensitive. (As custom headers are not interpreted by the MTA in the first place, but
are parsed by PHP, PHP < 4.3 only supported the Cc header element and was
case-sensitive).
4.2.3
The additional_parameters parameter is disabled in safe_mode and the mail() function
will expose a warning message and return FALSE when used.
4.0.5 The additional_parameters parameter was added.
Examples
Example #1 Sending mail.
Using mail() to send a simple email:
<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send
mail('caffeinated@example.com', 'My Subject', $message);
?>
Example #2 Sending mail with extra headers.
The addition of basic headers, telling the MUA the From and Reply-To addresses:
<?php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
PHP: mail - Manual http://php.net/manual/en/function.mail.php
5 of 51 6/17/2014 2:07 PM
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
Example #3 Sending mail with an additional command line parameter.
The additional_parameters parameter can be used to pass an additional parameter to the program
configured to use when sending mail using the sendmail_path.
<?php
mail('nobody@example.com', 'the subject', 'the message', null,
'-fwebmaster@example.com');
?>
Example #4 Sending HTML email
It is also possible to send HTML email with mail().
<?php
// multiple recipients
$to = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
PHP: mail - Manual http://php.net/manual/en/function.mail.php
6 of 51 6/17/2014 2:07 PM
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
Note:
If intending to send HTML or otherwise Complex mails, it is recommended to use the PEAR
package PEAR::Mail_Mime.
Notes
Note:
The Windows implementation of mail() differs in many ways from the Unix implementation.
First, it doesn't use a local binary for composing messages but only operates on direct sockets
which means a MTA is needed listening on a network socket (which can either on the
localhost or a remote machine).
Second, the custom headers like From:, Cc:, Bcc: and Date: are not interpreted by the MTA
in the first place, but are parsed by PHP.
As such, the to parameter should not be an address in the form of "Something
<someone@example.com>". The mail command may not parse this properly while talking
with the MTA.
Note:
It is worth noting that the mail() function is not suitable for larger volumes of email in a loop.
This function opens and closes an SMTP socket for each email, which is not very efficient.
For the sending of large amounts of email, see the PEAR::Mail, and PEAR::Mail_Queue
packages.
Note:
The following RFCs may be useful: RFC 1896, RFC 2045, RFC 2046, RFC 2047,
RFC 2048, RFC 2049, and RFC 2822.
See Also
imap_mail() - Send an email message
PEAR::Mail
PEAR::Mail_Mime
PHP: mail - Manual http://php.net/manual/en/function.mail.php
7 of 51 6/17/2014 2:07 PM
add a note
User Contributed Notes 88 notes
up
down
53
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
down
11
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 Franois 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
PHP: mail - Manual http://php.net/manual/en/function.mail.php
8 of 51 6/17/2014 2:07 PM
dans le Var.</p>
</body>
</html>
';
In this case Outlook will also "understand" that message is encoded using UTF-8.
up
down
7
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
down
5
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
down
5
antoine dot php dot net at bonnefoy dot eu
9 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);
?>
PHP: mail - Manual http://php.net/manual/en/function.mail.php
9 of 51 6/17/2014 2:07 PM
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;
PHP: mail - Manual http://php.net/manual/en/function.mail.php
10 of 51 6/17/2014 2:07 PM
// 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;
}
}
PHP: mail - Manual http://php.net/manual/en/function.mail.php
11 of 51 6/17/2014 2:07 PM
// Fin
$msg .= $rn . '--' . $boundary . '--' . $rn;
// Function mail()
mail($to, $subject, $msg, $headers);
}
}
?>
up
down
2
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
down
2
Porjo
3 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
down
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.
PHP: mail - Manual http://php.net/manual/en/function.mail.php
12 of 51 6/17/2014 2:07 PM
* "The maximum total length of a text line including the <CRLF> is 1000 characters"
(RFC 821)
up
down
1
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
down
1
Edward
4 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
down
3
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
PHP: mail - Manual http://php.net/manual/en/function.mail.php
13 of 51 6/17/2014 2:07 PM
(
'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
down
1
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
down
1
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
PHP: mail - Manual http://php.net/manual/en/function.mail.php
14 of 51 6/17/2014 2:07 PM
spaces
mail($to, 'the subject', 'the message');
?>
up
down
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
down
1
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)."=:"
PHP: mail - Manual http://php.net/manual/en/function.mail.php
15 of 51 6/17/2014 2:07 PM
.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
PHP: mail - Manual http://php.net/manual/en/function.mail.php
16 of 51 6/17/2014 2:07 PM
--$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
PHP: mail - Manual http://php.net/manual/en/function.mail.php
17 of 51 6/17/2014 2:07 PM
$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
down
1
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);
?>
PHP: mail - Manual http://php.net/manual/en/function.mail.php
18 of 51 6/17/2014 2:07 PM
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
down
0
pierreantoine dot covet at gmail dot com
2 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
down
0
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--
PHP: mail - Manual http://php.net/manual/en/function.mail.php
19 of 51 6/17/2014 2:07 PM
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
down
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
down
0
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:
PHP: mail - Manual http://php.net/manual/en/function.mail.php
20 of 51 6/17/2014 2:07 PM
$headers .= "Content-Type: text/plain; charset = \"UTF-8\";\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$headers .= "\n";
Greetings
up
down
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}--";
PHP: mail - Manual http://php.net/manual/en/function.mail.php
21 of 51 6/17/2014 2:07 PM
$returnpath = "-f" . $sendermail;
$ok = @mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return $i; } else { return 0; }
}
?>
up
down
0
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
down
0
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
down
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
down
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.
PHP: mail - Manual http://php.net/manual/en/function.mail.php
22 of 51 6/17/2014 2:07 PM
See:
http://www.faqs.org/rfcs/rfc2822 part 2.1.1.
up
down
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
down
0
panoramical at gmail dot com
7 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))
{
PHP: mail - Manual http://php.net/manual/en/function.mail.php
23 of 51 6/17/2014 2:07 PM

// 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];

}
PHP: mail - Manual http://php.net/manual/en/function.mail.php
24 of 51 6/17/2014 2:07 PM

}

}

}

}

// 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
down
PHP: mail - Manual http://php.net/manual/en/function.mail.php
25 of 51 6/17/2014 2:07 PM
0
Anonymous
7 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
down
0
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
down
0
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
PHP: mail - Manual http://php.net/manual/en/function.mail.php
26 of 51 6/17/2014 2:07 PM
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
down
0
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
down
0
Sven Riedel
9 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
down
0
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
down
-1
umangberi at gmail dot com
4 years ago
up
down
-1
martin dot farrow at versacloud dot com
PHP: mail - Manual http://php.net/manual/en/function.mail.php
27 of 51 6/17/2014 2:07 PM
1 year ago
up
down
-1
buraks78 at gmail dot com
3 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
28 of 51 6/17/2014 2:07 PM
up
down
-1
sander at cartel dot nl
7 years ago
up
down
-1
epheterson at gmail dot com
2 years ago
up
down
-1
php at caves dot org dot uk
4 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
29 of 51 6/17/2014 2:07 PM
up
down
-1
aldertb at XS4ALL dot nl
5 years ago
up
down
-1
Gianluigi_Zanettini-MegaLab.it
6 years ago
up
down
-1
bigtree at dontspam dot 29a dot nl
7 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
30 of 51 6/17/2014 2:07 PM
up
down
-1
thomas at p-devion dot de
7 years ago
up
down
-1
Anonymous
9 years ago
up
down
-1
stevenlim at Edinburgh-Consulting dot com
11 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
31 of 51 6/17/2014 2:07 PM
up
down
-4
krzysiek dot 333 at gmail dot com
2 years ago
up
down
-1
Tobias Christensen
6 months ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
32 of 51 6/17/2014 2:07 PM
up
down
-1
bburch at bouncingpixel dot com
1 year ago
up
down
-1
phadley at reliableid dot com
3 years ago
up
down
-1
rch+php at online dot lt
4 years ago
up
down
-1
dtbaker.com.au
4 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
33 of 51 6/17/2014 2:07 PM
up
down
-1
d dot r at usask dot ca
5 years ago
up
down
-1
alex_ramos at sourceforge dot net
5 years ago
up
down
-2
mulllhausen
2 years ago
up
down
-1
bob
5 years ago
up
down
-3
ABOMB
2 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
34 of 51 6/17/2014 2:07 PM
up
down
-2
php at ontheroad dot net dot nz
5 years ago
up
down
-1
Ben Cooke
8 years ago
up
down
-1
grey at greywyvern dot moc
9 years ago
up
down
-1
PHP: mail - Manual http://php.net/manual/en/function.mail.php
35 of 51 6/17/2014 2:07 PM
f dot touchard at laposte dot net
11 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
36 of 51 6/17/2014 2:07 PM
up
down
-3
Maven1 at example dot com
4 years ago
up
down
-3
webmaster at plumage dot nl
5 years ago
up
down
-3
Alex Jaspersen
7 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
37 of 51 6/17/2014 2:07 PM
PHP: mail - Manual http://php.net/manual/en/function.mail.php
38 of 51 6/17/2014 2:07 PM
up
down
-2
ittasks at gmail dot com
1 year ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
39 of 51 6/17/2014 2:07 PM
up
down
-2
Max AT
2 years ago
up
down
-2
saganwebdesign
2 years ago
up
down
-2
Michiel Uitdehaag
PHP: mail - Manual http://php.net/manual/en/function.mail.php
40 of 51 6/17/2014 2:07 PM
3 years ago
up
down
-2
Systemx
4 years ago
up
down
-2
Clayton Ginsburg
4 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
41 of 51 6/17/2014 2:07 PM
up
down
-2
Tomer
4 years ago
up
down
-2
Anonymous
4 years ago
up
down
-2
phpcoder at cyberpimp dot ig3 dot net
6 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
42 of 51 6/17/2014 2:07 PM
up
down
-2
johniskew2
7 years ago
up
down
-2
Nimlhug
8 years ago
up
down
-2
fontajos at phpeppershop dot com
8 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
43 of 51 6/17/2014 2:07 PM
up
down
-4
Alex M.
4 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
44 of 51 6/17/2014 2:07 PM
up
down
-2
Paul
10 years ago
up
down
-4
orjtor
5 years ago
up
down
-4
PHP: mail - Manual http://php.net/manual/en/function.mail.php
45 of 51 6/17/2014 2:07 PM
fnjordy at gmail dot com
8 years ago
up
down
-3
akger1379 at gmail dot com
2 years ago
up
down
-5
marcel dot portela at gmail dot com
5 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
46 of 51 6/17/2014 2:07 PM
up
down
-5
Josh
7 years ago
up
down
-3
mortoray at ecircle-ag dot com
6 years ago
up
down
-3
admin at chatfamy dot com
7 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
47 of 51 6/17/2014 2:07 PM
up
down
-3
tdaniel at univ dot haifa dot ac dot il
7 years ago
up
down
-3
junaid at techni-serve dot com
8 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
48 of 51 6/17/2014 2:07 PM
up
down
-5
debis at woh dot rr dot com
2 years ago
PHP: mail - Manual http://php.net/manual/en/function.mail.php
49 of 51 6/17/2014 2:07 PM
up
down
-7
me at arronwoods dot com
2 years ago
add a note
Mail Functions
ezmlm_hash
mail
Copyright 2001-2014 The PHP Group
My PHP.net
Contact
PHP: mail - Manual http://php.net/manual/en/function.mail.php
50 of 51 6/17/2014 2:07 PM
Other PHP.net sites
Mirror sites
Privacy policy
PHP: mail - Manual http://php.net/manual/en/function.mail.php
51 of 51 6/17/2014 2:07 PM

You might also like