PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<ldap_unbindezmlm_hash>
view the version of this page
Last updated: Sat, 19 Apr 2003

XLIX. Mail Funktionen

Die mail() Funktionen erlauben das Versenden von Mail.

Inhaltsverzeichnis
ezmlm_hash -- Calculate the hash value needed by EZMLM
mail -- Sende Mail


User Contributed Notes
Mail Funktionen
add a note
10-Nov-2001 09:35
For Windows users, you can likely set the SMTP directive in the php.ini configuration file to your isp's SMTP mail server - the same as you use for outgoing mail in your email client (Eudora, Outlook, etc.) . However, check with your ISP before doing this!

eg
SMTP = mail.your_isp.com

rossgerring at yahoo dot com
31-Jan-2002 03:26

the 'sendmail_from' string is the default 'from' address supplied with any outgoing mail if no other 'from' address has been supplied in the header section of the mail() function. In other words, setting the 'from' address in the mail() function overrides this setting.
lordkai at gmx dot net
23-Feb-2002 12:03

Check out Zend.com's code gallery under EMAIL, look for SMTP.

with the new class you can specify different hosts (with respective l/p) anytime you wish.

good for guys who hasn't got the mail() enabled (i think) but can at least open sockets.

again, i'm green at this, might be incorrect.

drtebi at yahoo dot com
03-Apr-2002 05:58

Hi there,
here is a little snippet that can be used in your mail script in order to check if the mail was really sent from the domain the message originated from:

// array for allowed domains (lower case please)
$referers = array('php.net', 'www.php.net', 'us2.php.net');

// add upper case referrers
$size = sizeof($referers);
for($i = 0; $i < $size; $i++){
 $referers[] = strtoupper($referers[$i]);
}

// check referers
for($i = 0; $i < sizeof($referers); $i++){
if(substr($HTTP_SERVER_VARS['HTTP_REFERER'], 7, strlen($referers[$i])) == $referers[$i]){
   $bad_referer = FALSE;
   break;
 }
else{
   $bad_referer = TRUE;
 }
}
if($bad_referer){
header('Location: );
exit;
}

I added the upper case domains, since once in a while surfers tend to write in all-caps.

Hope that helps someone :-)

DrTebi

gory at alphasoft-bg dot com
05-Apr-2002 02:28

Linux
Known situation mail() not work, but why ???

Try send a simple mail from shell
root@alpha:~# sendmail [email protected]
strange error ???

collect: Cannot write ./dfg35A7vav022304 (bfcommit, uid=XXX, gid=XXX): Permission denied

queueup: cannot create queue temp file ./tfg35A7vav022304, uid=XXX: Permission denied

Don't mess with permissons on /var/spool
/var/mail /var/spool/mqueue
Just set them follow the instructions from sendmail readme
It seems that when sendmail runs not like a daemon ( without -bd or -bD options ) it doesn't use corect QueueDirectory from /etc/mail/sendmail.cf

The solution is

set this line in php.ini
;For Unix only.You may supply arguments as well (default:'sendmail -t -i').

sendmail_path="/usr/sbin/sendmail -t -i -OQueueDirectory=/var/spool/mqueue/"

That's all. mail() now work fine :)))
Hope this will save up somebody's time, because i spent a lot of hours in digging and tearing my hair (and my mother will colapse if she hear what a words i use :)))

12-Apr-2002 03: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 [email protected]"

would set the default return-path for mail from that virtual host.

php at driekeerkiwi dot nl
20-May-2002 09:21

Dear all,

Setting up a system which will ask a new member to confirm he asked for it
by mailing him I experienced a problem. If a new member fills in a Hotmail
e-mailaddress he will receive my mail in his Junk Mail directory.

Many tips I found where telling te configure the php.ini on my server but
that is not enough. I use Apache on a Win32 so some things will be different
for you Linux people but the problems I experienced do not have anything to
do with that I believe.
But, configure your php.ini setting the mail functions, for Win32:

SMTP = mail.yourisp.com
sendmail_from = [email protected]

Now the most important.
When using mail() you should insert headers, and not just a few!!!
I give you an example I'm using.
Very important is also to include the ' To: ' header. I forgot this and when
I put it in my code Hotmail didn't refuse my e-mails anymore. Only when
people have there Junk Mail listed as "Exclusive". But when configured
"High" it will go ok.

Here the example:

$myname = "Me Myself";
$myemail = "[email protected]";

$contactname = "Mister Contact";
$contactemail = "[email protected]";

$message = "hello from happy me";
$subject = "A mail not refused by Hotmail";

$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: ".$myname." <".$myemail.">\r\n";
$headers .= "To: ".$contactname." <".$contactemail.">\r\n";
$headers .= "Reply-To: ".$myname." <$myreplyemail>\r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
$headers .= "X-Mailer: Just My Server";

mail($contactemail, $subject, $message, $headers);

I hope this helped someone.

Godfried van Loo
The Netherlands

smichels at intradat dot com
26-May-2002 02:30

mail will NOT work if your system doesn't have
a /bin/sh (like in chroots...)

just take some time to figure it out ;)

29-May-2002 01:15
I use qmail, and have found that mail() will return TRUE even if there is no valid email address in the To parameter. If you're having problems getting mail() to work with qmail, double-check that the output from your script produces a valid email message before looking further!
lanky at lankyland dot com
03-Jun-2002 04:11

i have noticed that the mail() doesnt work if you define some headers in a variable ($headers) and also within the mail( ..here..  ). this causes a conflict for some reason
example...

$headers = "MIME/TYPE blah blah blah";
$headers = "Cc: [email protected]";

mail("$headers", "From: [email protected]");

i hope this helps

aharradine at skychannel dot com dot au
06-Jun-2002 03:50

use these headers to send in html form

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

sergiopaternoster at tiscali dot it
12-Jun-2002 04:07

If you have downloaded an email via POP connection, ex.:
$complete_email ="
Date: Wed, 20 Jun 2001 20:18:47 -0400
From: "Sergio Paternoster" <[email protected]>
To: "My Users" <[email protected]>
Subject: Hello from Sergio!
MIME-Version: 1.0
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello from Sergio!
";
and want to forward it to another email address, just change the To: field into the encoded downloaded email and then use

mail("", "", "",$To_changed_complete_email);

mjt at jpeto dot net
26-Jun-2002 03:08

If some of your mails cannot be received by some people, you might have the following problem:

Some mailservers block messages with more than 1024 Characters in a single line.

Solution: just add a simple linebreak (\n) after the last space before each character 1024

You could possibly use wordwrap() for this...

daevid at daevid dot com
11-Jul-2002 12:35

in the excellent 'header' example:
[email protected]
20-May-2002 02:21

I find it better to use:

mail("", $subject, $message, $headers);

because you are already setting the TO: in the headers. If you put the $contactemail, you will see two names on the TO line on the email separated by ;

also, if it's not painfully obvious, use:
"Content-type: text/plain"
to get regular text vs. html text.

11-Jul-2002 08:06
Took some digging to find how to set the mail server port number as the typist of the documention above forgot to finish typing the Mail Configuration Directive "smtp_port".
feathern at yahoo dot com
09-Aug-2002 06:29

Solution to massmailing timeout:
Unsafe solution is to change the timeout properties in php.ini
The better solution is to create separate email object run through window command prompt (in windows) or separate shell function (in unix) that will run itself separately until termination.
[I found php to run faster in a shell/command prompt]

redy dot r at NOSPAMmadagascan dot com
16-Aug-2002 11:46

If you need to send an e-mail with an html content and the same e-mail have Bcc headers.
Place the Bcc (and why not also Cc) at the end of your additional headers. Otherwise, people receiving the email in copy may have the html code in their screen. The one who are designed as main recipient will not have this problem.

Explanation :
=========
The e-mail headers are broken when the PHP parser delete the Bcc line (Removed cause hidden, obvious !).

Example :
=======

This is bad

$header    = "From: \"".addslashes($sender_name)."\" <".$sender_email.">\r\n";
$header   .= "Reply-To: ".$sender_email."\r\n";
$header   .= "Cc: ".$other_email."\r\n";
$header   .= "Bcc: ".$another_email."\r\n";
$header   .= "MIME-Version: 1.0\r\n";
$header   .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$header   .= "X-Priority: 1\r\n";
$header   .= "X-Mailer: PHP / ".phpversion()."\r\n";

The following is good

$header    = "From: \"".addslashes($sender_name)."\" <".$sender_email.">\r\n";
$header   .= "Reply-To: ".$sender_email."\r\n";
$header   .= "MIME-Version: 1.0\r\n";
$header   .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$header   .= "X-Priority: 1\r\n";
$header   .= "X-Mailer: PHP / ".phpversion()."\r\n";
$header   .= "Cc: ".$other_email."\r\n";
$header   .= "Bcc: ".$another_email."\r\n";

Sorry for my bad english. :-)

Redy Ramamonjisoa
<[email protected]>

no dot grstarrett at spam dot cox dot net
19-Aug-2002 07:43

I had a problem with the outgoing email from PHP: The emails were going OUT but not being recieved by SOME users.

Specifically, users with accounts within my own ISP were fine (COX.NET), my .NAME account was OK, and others. AOL users got NOTHING as well as some other users.

The problem was was with PHP.INI settings. Notice the default setting:

sendmail_from = [email protected] ; for Win32 only

This affects the "return path" header (on my system anyway) REGARDLESS of the From header entry.  Apparently some anti-spam filters look at the return path to see if it is legit and, if not, drop the message.

If you leave this as is it will work fine... for SOME mail transports, but not all!! For it to work properly, I had to configure it to be an email address within the domain of my ISP. Note that I also have the SMTP server set to my ISP's main outgoing SMTP server. Apparently, any address will work as long as it is properly formatted and from the domain of the SMTP server.

My setting now reads similar to:

sendmail_from = [email protected] ; for Win32 only

I haven't verified it works in all cases, but it works at least for AOL. I'm fairly confident it will work for all my users, I'll try to remember to post more info if I find out anything else.

BTW: I didn't have to change the \r to \r\n with my configuration (XP/IIS5), but I have had trouble with that in other platforms (e.g. NT4/IIS4). You might want to look at that as well.

bschwaegerl at zen-works dot de
21-Aug-2002 03:11

This is an example 4 sending german umlaute - but it works 4 other special character settings, 2.

mail("[email protected]","Subject",
"Content",
"Mime-Version:1.0\nContent-Type: text/plain; charset=\"iso-8859-1\nContent-Transfer-Encoding: 8bit\"");

Regards,

Dipl.Inf. (FH) Bernd Schwaegerl
Mueller-Knoche GmbH, Systemhaus fuer EDV-Loesungen

a dot deak at anicon dot de
23-Aug-2002 01:13

When you got a "Server Error" you not allowed to send a EMail with you return address or to a specified EMail address.

Test it with "telnet (smtp server) smtp" and you get a 550 Relaying is prohibited Error.

regards

stevenlim at Edinburgh-Consulting dot com
06-Sep-2002 07:53

How to detect a bounce email

1. make sure the email you send out have the header
"Return-Path: [email protected]\r\n",
&
"Return-Receipt-To: [email protected]\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)

pvlasenko at hotmail dot com dot com
28-Sep-2002 10:04

If you find your self struggling with mail() function like I was you might want to send mail directly from your mailer and not through the mail() function. I was having hard time sending long(registration confirmation) messages with simple mail() function on Linux. My solution...

// Configuration
$announce_subject = "Message From Our Web Site";
$announce_from_email = "[email protected]";
$announce_from_name = "Our Site";
$announce_to_email = "[email protected]";
$body = "Announcement. Our site has a special offer today. Please visit. Thank you.";
$MP = "/usr/sbin/sendmail -t";
$spec_envelope = 1;
// Access Sendmail
// Conditionally match envelope address
if($spec_envelope)
{
$MP .= " -f $announce_from_email";
}
$fd = popen($MP,"w");
fputs($fd, "To: $announce_to_email\n");
fputs($fd, "From: $announce_from_name <$announce_from_email>\n");
fputs($fd, "Subject: $announce_subject\n");
fputs($fd, "X-Mailer: PHP4\n");
fputs($fd, $body);
pclose($fd);

Hope this helps you.
Pavel Vlasenko

zombie at localm dot org
29-Sep-2002 08:45

Note that in the above example of using sendmail that there must be a new line (\n) before the body starts. I scratched my head for a bit on this one. The messages were sending (even to aol) but the messages were blank, so i added the new line and it worked. The above example is much appriciated, thankyou thankyou.
pvlasenko at hotmail dot com
01-Oct-2002 02:20

I had trouble sending emails with mail()function some peple would get the emails then other would not, I had partialy solved this problem (see my post above) with avoiding mail function. It solved the problem but still for example hotmail would only get 3/10 sometimes 0/10 messages, I have now compleately solved this problem by adding ALL REQIRED headers and changing the sendmail path with envelope matching address ......

ini_set(sendmail_path, "/usr/sbin/sendmail -t -f [email protected]");

//Contents of an Registration Auto responce email(text format)
$message = "Thanks for registering".$userName;

$headers .= "From: Name<[email protected]>\n";
$headers .= "Reply-To: <[email protected]>\n";
$headers .= "X-Sender: <[email protected]>\n";
$headers .= "X-Mailer: PHP4\n"; //mailer
$headers .= "X-Priority: 3\n"; //1 UrgentMessage, 3 Normal
$headers .= "Return-Path: <[email protected]>\n";
mail($email,"Registration COnfirmation",wordwrap(stripslashes($message)),$headers);
//Uncomment this to send html format
//$headers .= "Content-Type: text/html; charset=iso-8859-1\n";
//$headers .= "cc: [email protected]\n"; // CC to
//$headers .= "bcc: [email protected]"; // BCCs to, separete multiple with commas [email protected], [email protected]

richard at richard-sumilang dot com
02-Oct-2002 08:41

Yeah setting the timeout in php.ini isnt always the safe and best solution. A better solution would be to just use the set_time_limit() function that is already provided in php. It's safer because it will only apply to that script.

Hope that helps and makes life easier.

oliver dot ahlberg at smp dot se
19-Oct-2002 05:52

I've found this quite convenient in mail functions distributing various newsletters with HTML content:

function mail_from_file($template) {
$to = "[email protected]";
$title = "A message";
$header = ""; // Found elsewhere
$message = join('',file($template));

mail($to,$title,$message,$header);
}

/* PHP Code Body */
mail_from_file("newsletters/news2002-10-15.html");

This is just a short snippet from my code, and you'll probably want to make some string replacements in the retrieved message templates to personalize the emails for your recipients.

moacir at uchicago dot edu
22-Oct-2002 10:01

If you're passing variables you got from somewhere else (like a form) into mail(), make sure they're chop()-ped, or else everything will only half-work, causing, at least in one rumoured instance, hours of fretting and scouring of webpages and newsgroups.

It's not the order of the headers, it's not the presence of asterisks in the Subject: line, it's because there are inopportune \ns hiding around

Dark_Spirit at beyondinfinit dot com
24-Oct-2002 08:20

I followed an example from Godfried van Loo and found an error in his code. Hotmail was sending my mail to the recipient's junk mail. I found out that if you remove the "To: " line from the header, hotmail sends the mail to the inbox. here is my code:

function SEND_HTML_MAIL($mail_info) {
$from_name = $mail_info["from_name"];
$from_address = $mail_info["from_address"];

$to_name = $mail_info["to_name"];
$to_address = $mail_info["to_name"]." <".$mail_info["to_address"].">";

$message = $mail_info["message"];
$subject = $mail_info["subject"];

$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: ".$from_name." <".$from_address.">\r\n";
$headers .= "Reply-To: ".$from_name." <".$from_address.">\r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
$headers .= "X-Mailer: iCEx Networks HTML-Mailer v1.0";

mail($to_address, $subject, $message, $headers);
}

I hope this code will help you out.

Simon Germain
www.beyondinfinit.com

anon at nospam dot com
29-Oct-2002 05:22

is your mail() not working/hangs???

check if you have a lot of queued files in /var/spool/clientmqueue ...
if that's the case then there might be something wrong with your sendmail conf (usually it's the domain)

if not, then check the permissions on the /var/spool/clientmqueue, I altered mine and after that it worked..

kieran dot huggins at rogers dot com
06-Nov-2002 04:52

Finally got MIME working with attachments and everything:

The following is an example of a plaintext/html e-mail with attachments

for the HTML code, I had to include the weird markup that outlook express 6 added when the message was sent, otherwise it wouldn't display properly.  Send a copy of the message to yourself and copy the source.

Also, the /n newlines are important, normal rules of HTML seem to go kinda wonky with e-mail...

Experiment with your mailer and try different stuff.

<?php

// some local variables
$from_name = "Sender Name";
$from_email = "[email protected]";
$to_name = "Recipient Name";
$to_email = "[email protected]";
$subject = "Fantastic Subject";

// headers need to be in the correct order...
$headers = "From: $from_name<$from_email>\n";
$headers .= "Reply-To: <$from_email>\n";
$headers .= "MIME-Version: 1.0\n";
// the following must be one line (post width too small)
$headers .= "Content-Type: multipart/related;
type=\"multipart/alternative\"; boundary=\"----
=MIME_BOUNDRY_main_message\"\n";
//
$headers .= "X-Sender: $from_name<$from_email>\n";
$headers .= "X-Mailer: PHP4\n"; //mailer
$headers .= "X-Priority: 3\n"; //1 UrgentMessage, 3 Normal
$headers .= "Return-Path: <$from_email>\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";

//plaintext section begins
$message = "------=MIME_BOUNDRY_message_parts\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";

// your text goes here
$message .= "blah blah -- plaintext version of the message\n";
$message .= "\n";

// html section begins
$message .= "------=MIME_BOUNDRY_message_parts\n";
$message .= "Content-Type: text/html;\n charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";

// your html goes here -- It didn't appear properly without
// the weird markup that outlook added after sending
$message .= "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n";
$message .= "<HTML><BODY>\n";
$message .= "blah blah -- html version of the message\n";

// look ma, I'm referencing an img attachment (see below)
// watch out for weird markup!!!
$message .= "<IMG src=3D\"cid:some_picture\">\n";
$message .= "</BODY></HTML>\n";
$message .= "\n";

// this ends the message part
$message .= "------=MIME_BOUNDRY_message_parts--\n";
$message .= "\n";

// now we add attachments (images, etc)
$message .= "------=MIME_BOUNDRY_main_message\n";
$message .= "Content-Type: image/gif; \n name=\"some_picture.gif\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-ID: <some_picture>\n";
$message .= "\n";
\\ (truncated for space)
$message .= "R0lGODlheAAZAKIHAMTExCQkJJOTk\n";
$message .= "eLo7wzDKSatVQ5R3u7dDUUjcZ34D\n";
$message .= "\n";
// etc...etc...etc...

//message ends
$message .= "------=MIME_BOUNDRY_main_message--\n";

// send the message :-)
mail("$to_name<$to_email>", $subject, $message, $headers);

?>

I hope this helps -- sorry for the long post!

Kieran

casdeiro at degalicia dot org
14-Nov-2002 06:20

Very strange behavior detected. Don't know if it's got to be with PHP, with SENDMAIL, with INI files or what, but it's true. Hope you can try in you own systems and find out where's the problem:

(In an on-line lottery system) trying to send (confirmation) messages like these:

mail("[email protected]", "Confirmacion compra boleto num. 034", $message, $headers)

...they all arrive OK, but when subject was *slightly* different, like this:

mail("[email protected]", "Confirmacion compra boleto num. 178", $message, $headers)

...the never arrived!

I detected the difference was when the character after the blank space after the dot, was a '0', it was sent OK, but when that character was 1,2,3... or any other number (not tried with letters), the were not sent at all!

At last I tried this:
mail("[email protected]", "Confirmacion compra boleto num. -178-", $message, $headers)

...and it worked allright!

Any idea of the reason for this strange behavior?

(I drove myself mad for hours until I detected why some of my messages were sent and others not.)

hilger at emotiv-design dot de
20-Nov-2002 05:43

attachments in mail function

I just wanted to add something useful to Kieran's note (06-Nov-2002 10:52):
you can automate  the attachment by reading the file into a variable with fopen and fread, then (important) base64_encode it and chunksplit it. It worked fine with all PDFs I tried - the attachment just gets a little bigger (around 35%).
In the example below I used Kierans script, but shortened it in some places. HTML version etc. can of course be added again.

$headers = "From: $from <$email>\n";
$headers .= "Reply-To: $from <$email>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"MIME_BOUNDRY\"\n";
$headers .= "X-Sender: $from_k <$email>\n";
$headers .= "X-Mailer: PHP4\n";
$headers .= "X-Priority: 3\n";
$headers .= "Return-Path: <$email>\n";
$headers .= "This is a multi-part message in MIME format.\n";

$message = "--MIME_BOUNDRY\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
// your text goes here
$message .= "blah blah -- plaintext version of the message\n";
$message .= "\n";
$message .= "--MIME_BOUNDRY\n";
$message .= "Content-Type: application/pdf; name=\"brilliant.pdf\"\n";
$message .= "Content-disposition: attachment\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "\n";
$message .= "$str\n";
$message .= "\n";
//message ends
$message .= "--MIME_BOUNDRY--\n";

hilger at emotiv-design dot de
20-Nov-2002 05:46

sorry I forgot to add the most imortant part:

// Example for reading the file that you attach:
$file_url = "virtual/pdf/file.pdf";
$fp = fopen($file_url,"r");
$str = fread($fp, filesize($file_url));
$str = chunk_split(base64_encode($str));

kieran dot huggins at rogers dot com
20-Nov-2002 09:24

Thanks Hilger - that will come in handy on my end.

Here's a great overview of the MIME spec from 1993:


Happy mailing! - Kieran

alex at bartl dot net
29-Nov-2002 06:25

/*
This might be some useful stuff to send out emails in either text
or html or multipart version, and attach one or more files or even
none to it. Inspired by Kieran's msg above, I thought it might be
useful to have a complete function for doing this, so it can be used
wherever it's needed. Anyway I am not too sure how this script will
behave under Windows.

{br} represent the HTML-tag for line break and should be replaced,
but I did not know how to not get the original tag  parsed here.

function SendMail($From, $FromName, $To, $ToName, $Subject, $Text, $Html, $AttmFiles)
$From      ... sender mail address like "[email protected]"
$FromName  ... sender name like "My Name"
$To        ... recipient mail address like "[email protected]"
$ToName    ... recipients name like "Your Name"
$Subject   ... subject of the mail like "This is my first testmail"
$Text      ... text version of the mail
$Html      ... html version of the mail
$AttmFiles ... array containing the filenames to attach like array("file1","file2")
*/

$TEXT="This is the first test\n in text format\n.";
$HTML="<font color=red>This is the first test in html format.</font>";
$ATTM=array("/home/myself/test/go.jpg",
          "/home/myself/test/SomeDoc.pdf");

SendMail(
"[email protected]","PHP Apache Webmailer", //sender
"[email protected]","Recipients Name",    //recipient
"Testmail",                               //subject
$TEXT,$HTML,$ATTM);                      //body and attachment(s)

function SendMail($From,$FromName,$To,$ToName,$Subject,$Text,$Html,$AttmFiles){
$OB="----=_OuterBoundary_000";
$IB="----=_InnerBoundery_001";
$Html=$Html?$Html:preg_replace("/\n/","{br}",$Text)
 or die("neither text nor html part present.");
$Text=$Text?$Text:"Sorry, but you need an html mailer to read this mail.";
$From or die("sender address missing");
$To or die("recipient address missing");

$headers ="MIME-Version: 1.0\r\n";
$headers.="From: ".$FromName." <".$From.">\n";
$headers.="To: ".$ToName." <".$To.">\n";
$headers.="Reply-To: ".$FromName." <".$From.">\n";
$headers.="X-Priority: 1\n";
$headers.="X-MSMail-Priority: High\n";
$headers.="X-Mailer: My PHP Mailer\n";
$headers.="Content-Type: multipart/mixed;\n\tboundary=\"".$OB."\"\n";

//Messages start with text/html alternatives in OB
$Msg ="This is a multi-part message in MIME format.\n";
$Msg.="\n--".$OB."\n";
$Msg.="Content-Type: multipart/alternative;\n\tboundary=\"".$IB."\"\n\n";

//plaintext section
$Msg.="\n--".$IB."\n";
$Msg.="Content-Type: text/plain;\n\tcharset=\"iso-8859-1\"\n";
$Msg.="Content-Transfer-Encoding: quoted-printable\n\n";
// plaintext goes here
$Msg.=$Text."\n\n";

// html section
$Msg.="\n--".$IB."\n";
$Msg.="Content-Type: text/html;\n\tcharset=\"iso-8859-1\"\n";
$Msg.="Content-Transfer-Encoding: base64\n\n";
// html goes here
$Msg.=chunk_split(base64_encode($Html))."\n\n";

// end of IB
$Msg.="\n--".$IB."--\n";

// attachments
if($AttmFiles){
 foreach($AttmFiles as $AttmFile){
 $patharray = explode ("/", $AttmFile);
  $FileName=$patharray[count($patharray)-1];
  $Msg.= "\n--".$OB."\n";
  $Msg.="Content-Type: application/octetstream;\n\tname=\"".$FileName."\"\n";
 $Msg.="Content-Transfer-Encoding: base64\n";
  $Msg.="Content-Disposition: attachment;\n\tfilename=\"".$FileName."\"\n\n";

 //file goes here
  $fd=fopen ($AttmFile, "r");
  $FileContent=fread($fd,filesize($AttmFile));
  fclose ($fd);
  $FileContent=chunk_split(base64_encode($FileContent));
  $Msg.=$FileContent;
  $Msg.="\n\n";
 }
}

//message ends
$Msg.="\n--".$OB."--\n";
mail($To,$Subject,$Msg,$headers);
//syslog(LOG_INFO,"Mail: Message sent to $ToName <$To>");
}

don (at) santiagosds.com
12-Dec-2002 10:01

I recently had a problem where random "!" were appearing in my html emails. The simple solution to this is to make sure you have line breaks thoughout your html email. My email was written as 1 line of html (I just sent the entire email as one string). I found that at the point where outlook express decided to word wrap in the html source not the actually email. A "!" will appear in the actual email. This was so annoying to me. And took me about a hour to track down. My solution was to just randomly insert \n into my html email message string.
mcmer at tor dot at
13-Dec-2002 11:41

Merak 4.4.2: must use "\r\n" instead of "\n"

On a Microsoft Windows 2000 Server running Merak 4.4.2 as MTA we had a problem using "\n" for newlines. When "\n" is used in a message body or subject, Merak still connects to the destination SMTP server but never delivers. Strange but true. We figured out that using "\r\n" instead of "\n" helps out... any explanations or similar experiences?

rune at imptech dot net
21-Dec-2002 09:13

If your using Postfix for SMTP on FreeBSD you MUST end header lines with \n and not \r\n. I'm not sure if this is true of other platforms but this is definitely the case on my FreeBSD server.

-=- RuneImp
ImpTech - Web Design & Hosting

gordon at kanazawa-gu dot ac dot jp
27-Dec-2002 07:29

PROBLEM:
non-ascii (e.g. Japanese, Korean) characters appear garbled in email subject/name headers BUT the php server is not enabled to use multi-byte functions (mb_send_mail etc.)

SOLUTION:
encode the non-ascii charaters using "=?$charset?B?".chunk_split(base64_encode($non_ascii_chars))."?="

EXAMPLE:
$charset = "iso-2202-jp"; // Japanese charater set

// encode names, as necessary
$to_name = encode("to's name in Japanese", $charset);
$cc_name = encode("cc's name in Japanese", $charset);
$bcc_name = encode("bcc's name in Japanese", $charset);
$from_name = encode("from's name in Japanese", $charset);

// create pretty email addresses, if possible
$to_email = create_email_address($to_name, "[email protected]");
$cc_email = create_email_address($cc_name, "[email protected]");
$bcc_email = create_email_address($bcc_name, "[email protected]");
$from_email = create_email_address($from_name, "[email protected]");

// create headers
$headers = "";
$headers .= create_email_header("Cc", $cc_email);
$headers .= create_email_header("Bcc", $bcc_email);
$headers .= create_email_header("From", $from_email);
$headers .= create_email_header("Reply-to", $from_email);

$message = "message in Japanese";
$subject = "subject in Japanese";

// send the email message with encoded subject and names
mail($to_email, encode($subject, $charset), $message, $headers);

function encode($str, $charset) {
 return ($str && $charset) ? "=?$charset?B?" . chunk_split(base64_encode($str)) . "?=" : $str;
 //
 // for more details on Message Header
 // Extensions for Non-ASCII Text see ...
 //
// linked to from:  
}
function create_email_header($name, $value) {
 return ($name && $value) ? "$name: $value\r\n" : "";
}
function create_email_address($name, $email) {
 return ($name) ? "$name <$email>" : "$email";
}

dropkernel at email dot com
01-Jan-2003 01:26

I found that if the email address contains both user-friendly name as well as the address, like:

   From: Some Sender<[email protected]>\r\n

the message will be delivered using mail(). In the other hand, if the address is as follows:

   From: [email protected]<[email protected]>\r\n

the message won't be delivered. In fact, if there is an @-character in the name-part of the address, the message fails to send. I wonder what other characters may cause this?

nimrod lehavi a_t hotmail d_o_t com
05-Jan-2003 08:42

when u whish to send an email in other languages (hebrew for example),
if you want the mail client to use the right charset,
specify it in the headers of the mail function - for example:

$to = "[email protected]";
$from = "[email protected]";
$subject = "subject";
$body = "<html><other HTML tags />charset here for logical hebrew</html>";

$headers="Content-Type:text/html;CHARSET=iso-8859-8-i\r\n";
$headers.="From:".$from."\r\n";

mail($to, $subject, $body, $headers);

gordon at kanazawa-gu dot ac dot jp
07-Jan-2003 01:07

Sorry, the function "encode" given above, which is supposed to encode non-ascii characters in an email header, does not work. See for a working version.
amoo_miki at yahoo dot com
11-Jan-2003 11:39

php all, Win32:

Getting the error, "sendmail_from" not set, or custom "From:" header missing.

you may have set it in your script, and you mat feel all the things are correct, i did too.
the problem was that the php.ini file was in c:\php, and NOT in %WINDOWS%\. copying the php.ini to the win dir, it works fine.

m dot toci at amnesty dot it
16-Jan-2003 03:59

Problems sending mail to some ISP.
("Format data error" in Sendmail log)

I had problems sending mails to some user using mail() function. When i tried to send mail to users of some isp (as katamail.it), mails were not delivered, and i had a "format data error" in the sendmail log.

I solved the problem changing the sendmail_path in php.ini to:

sendmail_path= /usr/sbin/sendmail -t -i -f [email protected]

where "[email protected]" is a valid e-mail addres on the local server.

hope it helps...

weljava at hotmail dot com
23-Jan-2003 04:07

When I comment the line ";sendmail_path =" ,my iGENUS work! and I link /usr/sbin/sendmail to /var/qmail/bin/sendmail .

good luck every one.

thomas at thomak dot de
24-Jan-2003 03:46

Hello
I had a problem sending email from UNIX using mail() and having:

ini_set(sendmail_path, "/usr/sbin/sendmail -t -f [email protected]");

in my PHP-mail program (not in setup).

Receivers server doesn't forward the message.
Now I use "-f " feature as a 5-th parameter in mail():
mail($recEmail,$subject, $message, $headers,"-f [email protected]");
Now it works well.
Found it on (in German)
works with PHP 4.0.5 upwards (write them).
:-) T.

zan at stargeek dot com
24-Jan-2003 04:47

here's the source code to an example of an email contact for that allows your visitors to send you emails from a webpage

Alper SARI
29-Jan-2003 01:23

I had a problem with the email from PHP.
If you use "to" in headers and mail function than receiver client will be shown adresses two times. So You have to use only in mail functions to solving this problem.

f dot touchard at laposte dot net
31-Jan-2003 02:46

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

ronan dot minguy at wanadoo dot fr
20-Feb-2003 03:45

If you want to send an email in HTML with accent letters (for non-only-english speaking people) or the euro sign, put this in your header :
Content-Type: text/html; charset=iso-8859-15

Ronan

tj
11-Mar-2003 03:41

Using IIS's CDONTS
------------------------------------------

I found a link here...


...which shows how to utilize the CDONTS COM
object when running PHP under IIS.

<?php
@$CDONTS = new COM("CDONTS.NewMail");

@$CDONTS->From = "[email protected]";
@$CDONTS->To = "[email protected]";
@$CDONTS->CC = "[email protected]";
@$CDONTS->BCC = "[email protected]";

@$CDONTS->BodyFormat = 0;
@$CDONTS->MailFormat = 0;

//@$CDONTS->AttachFile("c:\file.txt");

@$CDONTS->Subject = "Using CDONTS with PHP4 and IIS";
@$CDONTS->Body = "Blah blah blah blah, bleh...";

@$CDONTS->Send();
@$CDONTS->Close();

print "Mail sent";
?>

The only problem is (and this is where I am hoping
to get some input from others) when I run this code,
it received over 200 emails, and there were still
another 1000+ emails queued on the server (and that
was just when I was finally able to kill it).

Anyone have any explainations, or better examples?

Joscha
12-Mar-2003 10:53

Never forget the header
Content-type: text(/html); charset=iso-XXXX-XX\r\n"; (Where XXXX-XX stands for the charset and HTML is optional - don't write HTML when you send plain text mails)

If you forget to set this header, Outlook Express shows the mail correctly but Outlook has probs with it.

Outlook build 9: No newlines will appear in the mail
Outlook build 10: After every line a second newline will appear.

After setting the header, the mail will be shown correct in all email programs.

(Keywords: newline, outlook, outlook express, \n\r, \r\n, double newlines, no newline)

mfloryan at bigfoot dot com
21-Mar-2003 03:51

A brief comment on the "\r\n" in headers:
Recent email scanners (virus scanners) working on mail servers will refuse to deliver any mail containing the "\r" character in header (your mail will probably bounce off with "Disallowed MIME characters found in headers" comment).
This is true for Qmail-Scanner and F-Prot Antivirus for Linux but for others most probably too.
Hence use "\r\n" in headers ONLY when you send you email using the mail() function via Windows-based SMTP server - otherwise just use "\n"

msg000 at hotmail dot com
26-Mar-2003 10:09

I have been trying for several hours to attach a file to my email form. I was able to attach a file that is present in the www root directory easily. I viewed the mail and the attachment. however, when i try to attach a file from my PC I get an error. If somebody would help me in this since in all the above notes, I didn't find any note that states how should the path of a file found on the user's PC be written to be attached to a file.
I am trying to write the following:
<?
...
$attachment = "c:\\resume.doc";

$newmail = new CMailFile($subject,$to,$from,$message,$attachment,$mimetype);
$newmail->sendfile();
?>
Any help would be appreciated
Thank u in advance

info at van minus ed dot enel
28-Mar-2003 12:38

If you get an unexplainable exclamation mark (!) appearing
in the mail that you send using mail(),you are probally
sending a message wich has no newline characters (\n)

Fix this in your script or use this

$msg = wordwrap($msg, 72);

This will make sure that there are no excessively long
lines in your message, and thus remove that exclamation mark from your message.

ED

gdecaso at 2vias dot com dot ar
14-Apr-2003 08:42

When trying to use the mail() function under windows based systems, do NOT forget to complete the 'sendmail_from' with your valid e-mail address in your php.ini file. If not, you won't be able to send mails to anyone but yourself.
untold at punkass dot com
16-Apr-2003 09:13

Here's the final solution for me:


michael a at mac dott com
03-May-2003 06:57

If you are getting slash characters replacing single and double quotes and apostrophes - like ' becoming /' - then apparently there is an issue with your php.ini file.

But the easy way to fix it is to use the function 'stripcslashes'.

Just use:

<?php mail( $to , stripcslashes($subject) ,  stripcslashes($message) ...

Took me hours to find it.

Michael

grey at greywyvern dot com
09-May-2003 05:23

Here's a function I'm continually working at to send multiple emails while only opening the socket once (much faster than mail()) while sending a separate email to each address.  It also includes many headers which you can adjust to your liking.  Note the comment which explains the array format for incoming "To:" addresses.

function socketmail($toArray, $subject, $message) {
 // $toArray format --> array("Name1" => "address1", "Name2" => "address2", ...)

 ini_set(sendmail_from, "[email protected]");

 $connect = fsockopen (ini_get("SMTP"), ini_get("smtp_port"), $errno, $errstr, 30) or die("Could not talk to the sendmail server!");
   $rcv = fgets($connect, 1024);

 fputs($connect, "HELO {$_SERVER['SERVER_NAME']}\r\n");
   $rcv = fgets($connect, 1024);

 while (list($toKey, $toValue) = each($toArray)) {

  fputs($connect, "MAIL FROM:[email protected]\r\n");
    $rcv = fgets($connect, 1024);
   fputs($connect, "RCPT TO:$toValue\r\n");
     $rcv = fgets($connect, 1024);
  fputs($connect, "DATA\r\n");
     $rcv = fgets($connect, 1024);

   fputs($connect, "Subject: $subject\r\n");
   fputs($connect, "From: My Name <[email protected]>\r\n");
   fputs($connect, "To: $toKey  <$toValue>\r\n");
   fputs($connect, "X-Sender: <[email protected]>\r\n");
  fputs($connect, "Return-Path: <[email protected]>\r\n");
   fputs($connect, "Errors-To: <[email protected]>\r\n");
   fputs($connect, "X-Mailer: PHP\r\n");
   fputs($connect, "X-Priority: 3\r\n");
   fputs($connect, "Content-Type: text/plain; charset=iso-8859-1\r\n");
   fputs($connect, "\r\n");
   fputs($connect, stripslashes($message)." \r\n");

   fputs($connect, ".\r\n");
     $rcv = fgets($connect, 1024);
   fputs($connect, "RSET\r\n");
    $rcv = fgets($connect, 1024);
 }

 fputs ($connect, "QUIT\r\n");
   $rcv = fgets ($connect, 1024);
fclose($connect);
 ini_restore(sendmail_from);
}

add a note

<ldap_unbindezmlm_hash>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Wed May 14 01:12:44 2003 CEST