ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Facebook
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 24
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Z mojej strony serwisowi należy się bardzo mocna pochwała. Nawet późna pora zgłoszenia problemu (23.00) nie przeszkodziła Darkowi w jego rozwiązaniu. Do tego poziom odpisywania na maile jest bardzo wysoki... wszystko wykłada jak cierpliwy nauczyciel. Śmiało mogę przyznać, że zamieszczone na stronach porady są rzeczowo opisane - a nie jak to bywa w innych serwisach mamy sam kod i nic poza tym! Jeszcze raz wielkie dzięki!

Damian Jarosz
Adminer.pl

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

mail

(PHP 3, PHP 4, PHP 5)

mail -- Wysyła e-maila

Opis

bool mail ( string do, string temat, string treść [, string dodatkowe_nagłówki [, string dodatkowe_parametry]] )

mail() automatycznie wysyła wiadomość określoną w treść do odbiorcy określonego w do. Można wysłać wiadomość do kilku odbiorców na raz, wypisując ich adresy po przecinku w argumencie do. Poprzez tę funkcję można też wysłać listy zawierające załączniki lub inne typy wiadomości. Jest to możliwe dzięki kodowaniu MIME - po więcej informacji, zajrzyj http://www.zend.com/zend/spotlight/sendmimeemailpart1.php lub Klasy Mime PEAR.

Zapoznanie się z poniższymi RFC może być przydatne: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048 i RFC 2049.

mail() zwraca TRUE jeśli e-mail został zaakceptowany przez przekaźnik pocztowy do wysłania lub FALSE w przeciwnym wypadku.

Ostrzeżenie

Implementacja funkcji mail() w systemie Windows różni się od implementacji w systemie Unix. Po pierwsze, funkcja nie używa lokalnych programów do komponowania wiadomości pocztowych, tylko operuje na połączeniach socketowych, co oznacza, że do działania potrzebny jest Agent Transferu Poczty (MTA), który nasłuchuje na odpowiednim porcie. (Agent może znajdować się zarówno na maszynie lokalnej, jak i zdalnej). Po drugie, nagłówki użytkownika, takie jak From:, Cc:, Bcc: oraz Date: nie są w pierwszej kolejności interpretowane przez MTA, gdyż wcześniej są parsowane przez PHP. PHP < 4.3 obsługiwał spośród wyżej wymienionych tylko nagłówek Cc: (wymagana była odpowiednia wielkość liter); natomiast PHP <= 4.3 obsługuje już wszystkie wyżej wymienione nagłówki i nie wymaga odpowiedniej wielkości liter.

Przykład 1. Wysyłanie e-maila

mail("joecool@example.com", "Temat listu", "Linia 1\nLinia 2\nLinia 3");

Jeśli zostanie podany czwarty argument, będzie on dopisany na końcu nagłówka wiadomości. Ten argument wykorzystuje się do wstawienia dodatkowych nagłówków. Dodatkowe nagłówki rozdziela się znakiem powrotu karetki i nowego wiersza.

Notatka: Aby rozdzielić nagłówki, trzeba użyć sekwencji \r\n, chociaż niektóre uniksowe agenty pocztowe obsługują także pojedynczy znak nowej linii (\n).

Przykład 2. Wysyłanie listu z dodatkowymi nagłówkami.

mail("nobody@example.com", "temat", $wiadomosc,
     "From: webmaster@$SERVER_NAME\r\n"
    ."Reply-To: webmaster@$SERVER_NAME\r\n"
    ."X-Mailer: PHP/" . phpversion());

Argumentu dodatkowe_parametry używa się do przekazania dodatkowego paramteru do programu wysyłającego pocztę skonfigurowanego w dyrektywie sendmail_path. Używa się tego na przykład do ustawienia adresu zwrotnego koperty (envelope sender adress) przy wysyłaniu listu za pomocą sendmaila. Możesz być zmuszony dodać użytkownika jakim jest twój serwer www do listy zaufanych użytkowników w pliku konfiguracyjnym sendmaila, aby sendmail nie dodał nagłówka "X-warning" do wiadomości przy wysyłaniu koperty (envelope) tą metodą.

Przykład 3. Wysyłanie listu z dodatkowymi nagłówkami i przełącznikami.

mail("nobody@example.com", "temat", $wiadomosc,
     "From: webmaster@$SERVER_NAME", "-fwebmaster@$SERVER_NAME");

Notatka: Piąty argument funkcji mail() został dodany w PHP 4.0.5. Począwszy od PHP 4.2.3 argument ten jest zablokowany w trybie bezpiecznym. W przypadku próby użycia, funkcja mail() wygeneruje ostrzeżenie i zwróci FALSE.

Można tez użyć zwykłych operacji na łańcuchach znaków do tworzenia złożonych wiadomości e-mail.

Przykład 4. Wysyłanie złożonego e-maila.

/* adresaci */
$do  = "Marysia <marysia@example.com>" . ", " ; // zwróc uwagę na przecinek
$do .= "Kasia <kasia@example.com>";

/* temat */
$temat = "Przypomnienie o urodzinach w Sierpniu";

/* wiadomość */
$wiadomosc = '
<html>
<head>
 <title>Przypomnienie o urodzinach w Sierpniu</title>
</head>
<body>
<p>Te urodziny będziemy świętować w Sierpniu!</p>
<table>
 <tr>
  <th>Osoba</th><th>Dzień</th><th>Miesiąc</th><th>Rok</th>
 </tr>
 <tr>
  <td>Jan</td><td>3.</td><td>Sierpnia</td><td>1970</td>
 </tr>
 <tr>
  <td>Szymon</td><td>17.</td><td>Sierpnia</td><td>1973</td>
 </tr>
</table>
</body>
</html>
';

/* Aby wysłać e-mail w formacie HTML, należy ustawić nagłówek Content-type. */
$naglowki  = "MIME-Version: 1.0\r\n";
$naglowki .= "Content-type: text/html; charset=iso-8859-1\r\n";

/* dodatkowe nagłówki */
$naglowki .= "From: Przypominacz o urodzinach <urodziny@example.com>\r\n";

$naglowki .= "Cc: archiwum_mailingu@example.com\r\n";
$naglowki .= "Bcc: kontrola_mailingu@example.com\r\n";

/* a teraz wyślij */
mail($do, $temat, $wiadomosc, $naglowki);

Notatka: Upewnij się, że nie ma żadnych znaków nowej linii w argumencie do lub temat, gdyż w przeciwnym razie, e-mail może nie być wysłany poprawnie.

Notatka: Argument do nie może być adresem w postaci "Ktośtam <someone@example.com>". Funkcja mail() nie przetworzy prawidłowo takiego adresu w czasie transakcji z Agentem Transferu Poczty (MTA).

Patrz także: imap_mail().




User Contributed Notes

Hossein
25-Jan-2006 06:46

Hello firends,
Good article about email:

http://www.sitepoint.com/article/advanced-email-php

With regards,Hossein


krisdover at hotmail dot com
20-Jan-2006 08:25

#  Description: Simple class using php mail function to construct and send mime multipart
#                emails (i.e. emails with attachments) and support content-id style
#                embedded images in html messages
#
#  Limitations: Uses the ubiquitously supported 7bit (i.e. no encoding) message encoding where as
#                qouted-printable is recommended for html messages. Does not ensure that message
#                line lengths do not exceed the 998 character limit specified by RFC 2822.
#
#  Usage Example:
#    $mulmail = new multipartmail("krisd@work.net", "destination@anywhere.com", "Some Subject");
#    $cid = $mulmail->addattachment("/var/www/html/img/pic.jpg", "image/jpg");
#    $mulmail->addmessage(
#      "<html>\n" .
#      "  <head>\n" .
#      "  </head>\n" .
#      "  <body>\n" .
#      "  This is text before<img src=\"cid:$cid\"> and after\n" .
#      "  </body>\n" .
#      "</html>\n", "text/html");
#    $mulmail->sendmail();

   class multipartmail{
     var $header;
     var $parts;
     var $message;
     var $subject;
     var $to_address;
     var $boundary;

     function multipartmail($dest, $src, $sub){
         $this->to_address = $dest;
         $this->subject = $sub;
         $this->parts = array("");
         $this->boundary = "------------" . md5(uniqid(time()));
         $this->header = "From: $src\r\n" .
                         "MIME-Version: 1.0\r\n" .
                         "Content-Type: multipart/related;\n" .
                         " boundary=\"" . $this->boundary . "\"\r\n" .
                         "X-Mailer: PHP/" . phpversion();
     }

     function addmessage($msg = "", $ctype = "text/plain"){
         $this->parts[0] = "Content-Type: $ctype; charset=ISO-8859-1\r\n" .
                           "Content-Transfer-Encoding: 7bit\r\n" .
                           "\n" . $msg;
                           //chunk_split($msg, 68, "\n");
     }

     function addattachment($file, $ctype){
         $fname = substr(strrchr($file, "/"), 1);
         $data = file_get_contents($file);
         $i = count($this->parts);
         $content_id = "part$i." . sprintf("%09d", crc32($fname)) . strrchr($this->to_address, "@");
         $this->parts[$i] = "Content-Type: $ctype; name=\"$fname\"\r\n" .
                           "Content-Transfer-Encoding: base64\r\n" .
                           "Content-ID: <$content_id>\r\n" .
                           "Content-Disposition: inline;\n" .
                           " filename=\"$fname\"\r\n" .
                           "\n" .
                           chunk_split( base64_encode($data), 68, "\n");
         return $content_id;
     }

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

     /* to get the message body as a string */
     function getmessage(){
         $this->buildmessage();
         return $this->message;
     }

     function sendmail(){
         $this->buildmessage();
         mail($this->to_address, $this->subject, $this->message, $this->header);
     }
   }

?>
# inspired by code found here. thanks to all


corretge at gmail dot com
12-Dec-2005 10:19

A way to keep out spamers if in your form or script tell about From e-mail, and put it in the Header is (if the variable name is email):

$emiliu = $_REQUEST['email'];
if ( preg_match ( "/^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/", $emiliu) )
{
   OK  ... bla... bla.... bla

   $mailHead = "From: " . $_REQUEST['email'];
   mail($mailTO, $mailSbj, $mailBodyC . $mailBody, $mailHead);

}
else
{
  BAD HEADER
}


php at nioubi dot com
15-Nov-2005 12:43

For me, WinXP, EasyPHP 1.8.0.1, sending a mail with the headers lines separated by : \r\n
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

When I put the script online, and call it in order to send mail,
the html is displayed in the mail client (tested Outlook Express and Thunderbird) when you want to read the message sent by php. Some of the headers are considered like text (but it works when sent from local).

Solution : not use \r\n but only \n.


doom_blaster at hotmail dot com
12-Oct-2005 03:47

OK you gave good exemples but none look good with Lotus Notes 6.X. I found some exelent code compatible with Notes and others, the detailed solution is here :http://archivist.incutio.com/viewlist/css-discuss/37970

I have cleaned Rowan's text, this is my working code :

$boundary = md5(uniqid(time()));

$headers  = 'From: ' . $from . "\n";
$headers .= 'To: ' . $to . "\n";
$headers .= 'Return-Path: ' . $from . "\n";
$headers .= 'MIME-Version: 1.0' ."\n";
$headers .= 'Content-Type: multipart/alternative; boundary="' . $boundary . '"' . "\n\n";
$headers .= $body_simple . "\n";
$headers .= '--' . $boundary . "\n";
$headers .= 'Content-Type: text/plain; charset=ISO-8859-1' ."\n";
$headers .= 'Content-Transfer-Encoding: 8bit'. "\n\n";
$headers .= $body_plain . "\n";
$headers .= '--' . $boundary . "\n";
$headers .= 'Content-Type: text/HTML; charset=ISO-8859-1' ."\n";
$headers .= 'Content-Transfer-Encoding: 8bit'. "\n\n";
$headers .= $body_html . "\n";
$headers .= '--' . $boundary . "--\n";

$mailOk=mail('', $subject,'', $headers);

(Tested from Linux PHP4 to STMP Lotus Notes and Notes Client 6.5.1 & 5.? , it works with hotmail too, I didn't test other client)

by DitLePorc


GwarDrazul
15-Sep-2005 01:01

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/


Alan Hogan +PHP at pixels and pages ,com
03-Sep-2005 07:46

Header injection is a very real, common threat in which an attacker uses your mail form to send mail to whomever he chooses!  I've been hit, myself, and on a website with relatively little traffic!  Read more about it here:

http://securephp.damonkohler.com/index.php/Email_Injection


jfonseca at matarese dot com
26-Jul-2005 02:33

This is NOT PHP-specific but worth mentioning on the mail() page.

Watch out for sendmail command injection on your pages which call the mail() function.

How it works: the attacker will inject SMTP into your form unless you make it real clear where the header ends. Most people simply don't add a header or a \r\n\r\n sequence to their mail header forms.

Example : a new BCC: field can be injected so that your form can be used to deliver mail to any valid address the attacker chooses.

Since the httpd server host is a trusted host your MX will probably relay without asking any questions.

Be careful with any function that accepts user input.

Hope this helps.


a dot hari at softprosys dot com
25-Jul-2005 07:47

Guido, the same you can do like this.

while ($emailadresses = mysql_fetch_array($query, MYSQL_ASSOC)) {
   foreach ($emailadresses as $oneMailadres) {
       $recepientsArr[] = "$oneMailadres"; //build up the recepients array
   }
}
/* THIS IS NOT REQUIRED
// this is the tricky part: mail() will not sent to all the emailadresses, if you let your string end with ', ', so I used substr() to remove the last two characters from the string (comma and space).
$recepients = substr($recepients, 0, -2);
*/

//Instead...do this.
$recepients = implode(",", $recepientsArr[]);
//actual sending
mail($recepients, $subject, $mailbody, "From: $senderAddress");


Guido
19-Jul-2005 11:21

When you want to sent mail to emailadresses that you've got stored in a database, one can use this code (at least it's been usefull to me ;):

// fetch adresses from database
while ($emailadresses = mysql_fetch_array($query, MYSQL_ASSOC)) {
   foreach ($emailadresses as $oneMailadres) {
       $recepients .= "$oneMailadres"; //build up the recepient string
       $recepients = $recepients . ", ";
   }
}
// this is the tricky part: mail() will not sent to all the emailadresses, if you let your string end with ', ', so I used substr() to remove the last two characters from the string (comma and space).
$recepients = substr($recepients, 0, -2);
//actual sending
mail($recepients, $subject, $mailbody, "From: $senderAddress");


gregBOGUS at BOGUSlorriman dot com
21-Jun-2005 12:02

In the posting "gregBOGUS at BOGUSlorriman dot com 6th april 2005" I claimed that redirecting an email, via the mail() function, to a different email address was as simple as copying over the unmodified headers of the originally recieved email (which would, of course, include the original "To:" field).

However it seems that this works for a Xampp install (http://www.apachefriends.org/en/xampp.html) with Mercury as the mail agent, but doesn't work on my webhost without first removing the old "To:" field, and perhaps other header modifications. Therefore it looks like it would be safest to strip any header lines that shouldn't be there. <sigh>

http://www.lorriman.com


tarlrules at users dot sourceforge dot net
16-Jun-2005 08:26

You may also want to take a look at email() a mail() clone with built in MTA. This is particually useful if you webhost does has dissable access to mail.

email() is avaliable here: http://poss.sourceforge.net/email along with a php.net style function referance http://poss.sf.net/email/index.php?type=Documentation&page=email

Hope that help someone.

Jason


macronesia at macronesia dot net
15-Jun-2005 06:25

After doing some conductive testing, I have found that the popular GMail E-Mail system throws a 550 error when you send mail with the 'to' argument in the "User <user@example.com>" format.

I spent about twenty minutes bothering with it, and then just added the "user@example" argument, which works fine.

Just a note to save other people time. It might, however, work with sending E-Mail to people in my original format in a header.


javier at zincro dot com
31-May-2005 06:48

This might be something obvious, but it gave me a lot of headache to find out:

If you use an ascii char#0 in the "string mensaje" parameter, it will truncate the message till that point, (this happened to me sending a message read from a file)

For example:
<?
$hs_email
="blabla@blabla.com";
$hs_asunto="a message for you";

$hs_contenido="beginofcontent_";
$hs_contenido.=chr(0);
$hs_contenido.="_endofcontent";

mail($hs_email,$hs_asunto,$hs_contenido);
?>

Will result in an email that only contains the string:

beginofcontent_

Anyway, just in case it can save someone some time...


msheldon at desertraven dot com
15-May-2005 09:09

Just a comment on some of the examples, and as a note for those who may be unaware. The SMTP RFC 822 is VERY explicit in stating that \r\n is the ONLY acceptable line break format in the headers, though is a little vague about the message body. While many MTAs will deal with just \n, I've run accross plenty of them that will exhibit "interesting" behaviours when this happens. Those MTAs that are strict in compliance will definitely break when header lines are terminated with only \n. They will also most likely break if the body of the message contains more than 1000 consecutive characters without a \r\n.*

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

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

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

* "The maximum total length of a text line including the <CRLF> is 1000 characters" (RFC 821)


v152535 at mail dot ru (Vladimir)
09-May-2005 03:03

Good Example from http://docs.com.ru/php_3.php :
Send file.zip on 333@mail.ru .
File file.zip  inheres beside this php:

<?php

class mime_mail {
var
$parts;
var
$to;
var
$from;
var
$headers;
var
$subject;
var
$body;

//

 

 
  © 1996-2010 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt