You get a bonus - 1 coin for daily activity. Now you have 1 coin

Sending mail using PHP in linux or windows

Lecture



1. How to send a letter using PHP
2. How to send a letter with attachment (attachment), review of PEAR
3. How to send a letter with pictures
4. Alternative ways to send emails.
5. How to configure the server
5.1 How to set up a Linux server
5.2 How to set up a Windows server
5.3 How to make a web access to mail
6. MIME in section
7. Source Code Examples
7.1 Sending emails with attachments
7.2 Using Sockets
7.3 Using sendmail
7.3 Using ActiveX

1. How to send a letter using PHP

The easiest way to send a letter using PHP is to use the standard mail function. It has the following syntax:

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

Required parameters:

  • Recipient's e-mail
  • Letter title
  • Text of the letter

Optional parameters:

  • Additional headers
  • Additional command line options

Return Value ::

  • true if the letter was accepted for delivery
  • false otherwise.

The simplest example of its use is as follows:

mail("joecool@example.com", "My Subject", "Line 1\nLine 2\nLine 3");
?>

If you get the error "Fatal error: Call to undefined function: mail ()" on the screen, it means that either PHP was compiled without support for the mail function, or it is prohibited by the server settings. This practice has recently been widely distributed on free hosting servers. If you encounter such a problem, use the opportunity to send letters using sockets (sockets), described in detail in the section "alternative ways to send letters." In case you are a system administrator, refer to the section "How to configure the server" and try to fix this problem as such.

Additional headers can be used to specify the letter encoding, the sender's address, the return address, and many other options. They must be separated by a line break: the combination "\ r \ n". For example:

mail("nobody@example.com", "the subject", $message,
"From: webmaster@ example.com \r\n"
."X-Mailer: PHP/" . phpversion());
?>

Let us turn to a more complex example. The previous scripts worked with the text / plain format, now we will try to send mail in HTML format to several recipients with the encoding indicated:

$to = "Mary <mary@example.com>, " ;
$to .= "Kelly <kelly@example.com>";

$subject = "Birthday Reminders for August";

$message = '




Birthday Reminders for August

Here are the birthdays upcoming in August!


';

$headers = "Content-type: text/html; charset=windows-1251 \r\n";
$headers .= "From: Birthday Reminder \r\n";
$headers .= "Bcc: birthday-archive@example.com\r\n";

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

Comments for example: first we determine who the letter is addressed to. If there are several recipients, their addresses are indicated in one line and are separated by commas. When specifying the title and body of the letter, make sure that the encoding in which they were actually written coincided with the charset stated in the header.

In our example, the $ headers variable consists of four lines: in the first two we specify the type of the email being sent - HTML - and its encoding. In the next two lines we indicate the address of the sender and the address to which you should send a hidden copy of the letter.

One of the most frequently encountered problems when sending mail to koi8 is the formation of the message header. To solve this problem, you need to use the following code, which translates the string encoded in win-1251 into the header that most koi8 email clients understand.

$subject = '=?koi8-r?B?'.base64_encode(convert_cyr_string($subject, "w","k")).'?=';
?>

For example, the heading "Mail notification" will look like

  =? koi8-r? B? 8M / e1M / Xz8Ug1dfFxM / NzMXOycU =? = 

If you did everything correctly, and the recipient does not receive the letter (remember that the time costs for delivering the letter depend on many factors and can vary from several minutes to several hours), make sure that it really went. This must be done in 2 stages. First try the code:

if (mail("nobody@example.com", "the subject", "Example message",
"From: webmaster@example.com \r\n")) {
echo "messege acepted for delivery";
} else {
echo "some error happen";
}
?>

If you have already received an error at this step, it may mean that you either have not started sendmail (or another transport agent), or it is incorrectly configured, or there are errors in php.ini. For example, recently it has been a common rule not to accept letters that do not contain the correct Mail-from header.

In case the message was accepted for sending, try to look at the file / var / log / mail or ask your administrator for this, as this requires the rights of the supervisor (root). This can be done with the command tail / var / log / mail. In case of successful sending of the letter, the lines of the type below or an error message should appear in the log file:

Oct 2 00:21:02 l72 sendmail [131]: h91LL1DG000131: to = root, ctladdr = root (0/0), delay = 00: 00: 01, xdelay = 00: 00: 01, mailer = relay, pri = 30225, relay = [127.0.0.1] [127.0.0.1], dsn = 2.0.0, stat = Sent (h91LL1g1000134 Message accepted for delivery)
Oct 2 00:21:18 l72 sendmail [137]: h91LL1g1000134: to = , ctladdr = (0/0), delay = 00: 00: 17, xdelay = 00: 00: 16, mailer = local, pri = 30774, dsn = 2.0.0, stat = Sent

In any case, try to see the section "How to configure the server."

2. How to send a letter with attachment

Such a task faced a huge number of developers and, as a result, there is a huge number of ready-made solutions. Most of them contain various kinds of errors, do not implement all the functionality or are difficult to use. But the most significant minus - the overwhelming majority of developers after writing a class that meets his personal needs of the day, never again return to the support and refinement of the source code.

In this regard, further code samples will be based on a ready-made solution taken from PEAR (repository of applications and PHP modules). The package that will be used in the examples is called Mail_Mime. Download the latest version of the package and get comprehensive documentation at http://pear.php.net/package/Mail_Mime. Consider an example of its use:

include('Mail.php');
include('Mail/mime.php');

$text = 'Text version of email';
$html = '

HTML version of email';
$file = '/home/richard/example.php';
$crlf = "\r\n";
$hdrs = array(
'From' => 'you@yourdomain.com',
'Subject' => 'Test mime message'
);

$mime = new Mail_mime($crlf);

$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');

$body = $mime->get();
$hdrs = $mime->headers($hdrs);

$mail =& Mail::factory('mail');
$mail->send('postmaster@localhost', $hdrs, $body);
?>

The above code is quite understandable, but still a few words about it.

The $ mime variable is an instance of the Mail_mime class. In its constructor, we passed an optional parameter that determines which line feed will be used: "\ n" or "\ r \ n". This class is designed to form the body and headers of the letter sent. Using the setTXTBody method, we define the text part of the letter. As a parameter, the method takes a string or the name of the file to be used. Similarly, using the setHTMLBody method, we set the content of the HTML version of the letter.

Consider the addAttachment method in more detail. Accepted Parameters:

  • string $ data

    Full path to the attached file on the server or its contents. Required.

  • string $ c_type

    The value of the Content-type header to be sent. Optional parameter, the default value is application / octet-stream.

  • string $ name

    The name of the attached file. It will be used only if the first parameter ($ data) is the contents of the file.

  • boolean $ isfile

    Determines whether the first parameter is a file path. Optional parameter, the default value is true.

  • string $ encoding

    The value of the Content-Transfer-Encoding header, which determines the format in which the application will be sent. Optional parameter. Valid values ​​are base64 (used for binary files), quoted-printable (used for text files). The default value is base64.

Thus, there are two ways to apply this method.

  1. specifying the path to the file on the server:
      $ mime-> addAttachment ('/ home / user / report.txt', 'text / plain'); 
  2. indicating the contents of the file (in this case, the third and fourth parameters must be specified forcibly):
      $ mime-> addAttachment ($ contentFile, 'text / plain', 'report.txt', false); 

We proceed to the formation of the title and body of the letter. These are still the responsibilities of an instance of the Mail_mime class. The get method is used to form the letter body, which takes an associative array as an optional parameter. The keys can be the following values: text_encoding, html_encoding, 7bit_wrap, text_charset, html_charset. The headers method is used to form the headers. Accepts a hash array as an optional parameter. For more details on valid values ​​for this parameter, refer to RFC-822.

The call to the get () method must take place before the headers () method is called. Make sure that this condition is met in your code.

The process of sending an already generated letter is assigned to the Mail class. First you need to create an instance of this class using the static method call factory. In our example, it takes a single parameter - the string 'mail'. More detailed parameters and their values ​​are described below in the article, which describes alternative ways to send mail.

The process of sending mail is completed by calling the send method, which takes as an input parameter the list of recipients, the message headers and its body.

Checking for errors while sending a letter can be implemented using the following code:

$status =$mailer->send('user@your.domain.com', $headers, 'your message');
if (PEAR::isError($status)) {
print("***ERROR");
}
?>

For further acquaintance with the possibilities of the classes Mail and Mime_mail, see the sections "How to send a letter with pictures", "Alternative ways of sending letters"

3. How to send a letter with pictures

Sending a letter with an attachment and sending an HTML letter with an attachment are significantly different in nature. Of course, both those and those are in the body of the letter, encoded in base64, but the headers used in both cases are different. This section describes how to send an HTML file with embedded (as opposed to attached) images using the Mime_mail class. It is understood that you have already read the previous section.

include('Mail.php');
include('Mail/mime.php');

$text = 'Text version of email';
$html = '

HTML version of emailSending mail using PHP in linux or windows';
$file = '/tmp/image.jpg';
$crlf = "\r\n";
$hdrs = array(
'From' => 'you@yourdomain.com',
'Subject' => 'Test mime message'
);

$mime = new Mail_mime($crlf);

$mime->setTXTBody($text);
$mime->addHTMLImage ($file, 'image/jpeg');
$mime->setHTMLBody($html);

$body = $mime->get();
$hdrs = $mime->headers($hdrs);


$mail =& Mail::factory('mail');
$mail->send('postmaster@localhost', $hdrs, $body);
?>

The difference between this example and the one in the previous chapter is the use of the addHTMLImage function. It takes the following parameters:

  • string $ data

    full path to the attached image on the server or its contents. Required.

  • string $ c_type

    the content-type header value to be sent. Optional parameter, default value: application / octet-stream.

  • string $ name

    the name of the attached image. It will be used only if the first parameter ($ data) is the contents of the file.

  • boolean $ isfile

    determines whether the first parameter is an image path. Optional parameter, default value: true.

Similar to the addAttachment method, there are two ways to call this method: as the first parameter, you can specify the path to the image or binary image data. In the second case, the third and fourth parameters are mandatory.

The peculiarity of this method lies in the fact that each image using the Content-ID header : <8820c4185> is assigned a unique key. After that, all links to the attached image are replaced by links to its key. As a result, in the letter that came to the recipient there will be a line of the form Sending mail using PHP in linux or windows , which the mail client will analyze, extract the contents from the corresponding section of the letter and "show the picture".

A more detailed description of MIME headers is provided in the section "MIME in section".

4. Alternative ways to send emails.

Today, the following methods of sending emails from php scripts are common:

  • By calling the mail function
  • Directly by calling sendmail
  • Using sockets
  • Using a COM Object

The first three methods are implemented in the class PEAR :: Mail, which was described above. An instance of this class must be created by means of a static call to the factory method (the so-called "factory pattern"). The first parameter of the method determines the method of sending the letter, it can take one of the following values: mail, sendmail, smtp. The second parameter is an array, the content of which depends on the value of the first parameter:

  • 'Mail' value — send by calling standard function, no additional parameters
  • The value of 'sendmail' is sending directly by calling sendmail. Available advanced options:
    • sendmail_path - path to the program on the server;
    • sendmail_args - additional parameters for the command line.
  • The value of 'smtp' is sending mail using sockets. Available advanced options:
    • host - the IP address or domain name of the server running the mail transport agent that is ready to receive mail, for example localhost (for a local server) or mxs.mail.ru (for a public server);
    • port - the port on which it is running, usually the 25th one;
    • auth is a Boolean value that indicates the need for SMTP authentication, the default value is false;
    • username - used only with SMTP authentication, login on the server;
    • password - used only with SMTP authentication, password on the server.

An example of using the class PEAR :: Mail

$mail =& Mail::factory('smtp', array('host' => 'localhost', 'port' => 25));
$mail->send('postmaster@localhost', $hdrs, $body);
?>

The annex to this article provides examples of source codes that implement all of the listed ways to send mail without using the PEAR :: Mail class.

5. How to configure the server

5.1 How to set up a Linux server

If you come to the reading of this section, it means that you have decided to send mail by means of the transport mail agent (MTA) installed on your server, and encountered problems.

Do not forget that sending mail using sockets does not require an installed MTA, but allows you to use any server available to you that is ready to receive mail, for example, mxs.mail.ru.

If you get the error "Fatal error: Call to undefined function: mail ()" , it means that either PHP was compiled without support for the mail function, or it is prohibited by the server settings. The first may occur if during the build the configure script could not find sendmail. Make sure the path to sendmail is in the PATH environment variable, and try rebuilding PHP. Also look at the value of the disable_functions variable in the php.ini file.

In case letters are accepted for sending, but this is all over, make sure that you are running Sendmail (or any other MTA). To do this, try running `telnet localhost 25` and if you get" telnet: connect to address 127.0.0.1: Connection refused "instead of the expected" Connected to localhost. ", This means that you have problems with the MTA. Installation and configuration of post transport agents is not described in this article; use specialized manuals.

If the attempt to access port 25 was successful, try the following session:

  l72: ~ # telnet localhost 25
 Trying :: 1 ...
 telnet: connect to address :: 1: Connection refused
 Trying 127.0.0.1 ...
 Connected to localhost.
 Escape character is '^]'.
 220 utel.us ESMTP Sendmail /8.12.7/Linux 0.6;  Wed, Oct 22, 2003 4:10:45 pm +0300
 helo localhost
 250 72.utel.us Hello localhost [127.0.0.1], pleased to meet you
 mail from: nobody @ localhost
 250 2.1.0 nobody @ localhost ... Sender ok
 rcpt to: nobody @ localhost
 250 2.1.5 nobody @ localhost ... Recipient ok
 DATA
 354 Enter mail, end with "."  on a line by itself
 Helo world
 .
 250 2.0.0 h9MDAj1B009029 Message accepted for delivery
 quit
 Connection closed by foreign host.

This example demonstrates a successful mailing session. In case of errors (for example, the correct address of the sender is required in the "mail from" line), sendmail will issue a warning and ask you to repeat the entered string.

If letters are sent from the command line successfully, but not with php, try experimenting with the fourth parameter of the mail function or with the sendmail_path setting in the php.ini file

5.2 How to set up a Windows server

First you need to decide which SMTP server you want to use. This can be your personal PC or any other. Whichever method you choose, you need to set the SMTP variables, smtp_port, which define the settings of the server sending the mail. Also set the sendmail_from variable that defines the return address of the sender.

Further instructions apply only to those who decide to use their personal PC as an outgoing mail server.

Check if anyone is responding on port 25m. This can be done by running `telnet localhost 25`. If you received "Connection refused", it means that you do not have a mail agent running, and, most likely, it is not installed. In this case, you need to visit one of the following resources:

  • http://www.argosoft.com/applications/mailserver/
  • http://courierms.narod.ru/
  • http://www.indigostar.com/sendmail.htm

Choose a program that meets your needs, and then follow the instructions for installing and using it.

For example, we give instructions for setting up the first of them:

  1. Download and install ArGoSoft Mail Server
  2. Launch the application and select Tools> Options
  3. Choose a DNS server or provide the ability to determine it automatically.
  4. In the tab "IP Homes" lead 127.0.0.1
  5. Start the ArGoSoft Mail Server service and make sure that there were no error messages.
  6. In the php.ini file specify SMTP = localhost

5.3 How to make a web access to mail

Visit one of the following resources:

  • http://www.squirrelmail.org/
  • http://www.horde.org/

On any of them you will find all the necessary scripts and detailed instructions for installation and configuration.

6. MIME in section

Based on the free translation of the article "Sending MIME e-mail from PHP"

For more information about MIME you can read here http://book.itep.ru/4/4/mime.htm.

Initially, when mail was in its infancy, no MIME existed. It appeared somewhat later as an extension to the RFC-822 standard. Currently, any sent email, even if it does not contain any attachments, somehow uses MIME.

At first, the letter was understood as a linear text message, the contents of which can be read by viewing its source code. The MIME extension allows you to define specific attributes within a letter: the type of information transmitted, the way it is encoded, and recommendations for display. Also allows you to split the letter into independent sections and set individual attributes for each of them.

To illustrate the difference, consider two examples that contain the same letter in two different ways: an ordinary letter according to the RFC-822 standard and the same letter, but using MIME

  From: "John Coggeshall" 
 To: Joe Users 
 Subject: Hello from John!
 Date: Wed, 20 Jun 2001 20:18:47
 Message-ID: <1234@local.machine.example>
 Our you with a brush!
  From: "John Coggeshall" 
 To: Joe Users 
 Subject: Hello from John!
 Date: Wed, 20 Jun 2001 20:18:47
 Message-ID: <1234@local.machine.example>
 MIME-Version: 1.0
 Content-Type: text / plain;  charset = "iso-8859-1"
 Content-Transfer-Encoding: 7bit
 Our you with a brush!

The difference in the letters is obvious: the second example uses three additional headers. Mandatory of them is only the first: MIME-Version. Of greatest interest to us is the Content-Type header, by changing which we can transmit arbitrary types of documents.

  From: "John Coggeshall" 
 To: Joe Users 
 Subject: Hello from John!
 Date: Wed, 20 Jun 2001 20:18:47
 Message-ID: <000d01c0f9e7 $ bee1bb00 $ 8a22f340 @ oemcomputer>
 MIME-Version: 1.0
 Content-Type: image / jpeg;  name = 'zendlogo.jpg' 
 Content-Transfer-Encoding: base64
 

The base64 data itself has been omitted in the example. The disadvantage of the above example is the inability to insert a text part, since all the following data are interpreted as figure data.

If you have a task to send several different objects in one letter (for example, a text part and an attached picture), you should use the Content-Type: multipart / mixed header, which means that the letter consists of several segments. It is also necessary to define the boundary parameter, which will designate the boundary between the fragments. In most cases, its real value can be chosen arbitrarily. Each fragment is completed with a separate set of headers. Note that the MIME-Version header should be one for the whole letter and cannot be found in any of its parts. Let us give an example of a letter consisting of two parts: a text message and an attached image:

  From: "John Coggeshall" 
 To: Joe Users 
 Subject: Hello from John!
 Date: Wed, 20 Jun 2001 20:18:47
 Message-ID: <000d01c0f9e7 $ bee1bb00 $ 8a22f340 @ oemcomputer>
 MIME-Version: 1.0
 Content-Type: multipart / mixed;  boundary = "ZEND-12345";
 Content-Transfer-Encoding: 7bit
 This part of the E-mail should never be seen.  If
 you are reading this, consider upgrading your e-mail
client to a MIME-compatible client.
--ZEND-12345
Content-Type: text / plain; charset = "iso-8859-1"
Content-Transfer-Encoding: 7bit
 Hello! Here's that Zend.com logo!
-John
--ZEND-12345
Content-Type: image / jpeg; name = "zendlogo.jpg";
Content-Transfer-Encoding: base64
Content-Disposition: attachment

--ZEND-12345--

This is the simplest example of a multi-part MIME letter. The first one is of type text / plain and contains the actual content of the letter. The second part is of type image / jpeg and contains a base64-encoded image called zendlogo.jpg

When using a composite letter, remember:

  • The primary content-type header is set to multipart / mixed. He tells the client mail program that the letter consists of several segments, each of which has its own content-type header;
  • Значение атрибута boundary определенного в первичном заголовке content-type используется для разделения сегментов письма (так называемый маркер границы).

При использовании атрибута boundary постарайтесь, чтобы он был максимально уникален и не встречался в теле самого письма, так как в противном случае письмо будет неправильно разбито на составляющие части. Кроме того, маркер границы должен начинаться с двух дефисов, а в последнем своем вхождении, заканчивая письмо, он также заканчивается двумя дефисами. Заголовку, содержащему атрибут boundary, должны предшествовать два перевода строк, а последний маркер, означающий конец MIME-письма, должен также заканчиваться двумя переводами строк.

Второй сегмент письма содержит дополнительный заголовок Content-Disposition. Он используется для того, чтобы сообщить почтовой программе клиента, как визуально следует отобразить данный сегмент письма. Он может принимать значение как attachment (не является частью письма, прикрепленный документ), так и inline (включение, непосредственно связанное с телом письма, например картинка, вставленная в HTML). Также допустимо использование заголовка Content-Description для краткого описания прикрепленного файла.

Значение multipart/alternative атрибута Content-Type по синтаксису абсолютно идентично multipart/mixed, описанному выше. Его назначение - обеспечить несколько вариантов отображения одного и того же содержания (вместо соединения трех различных документов, как в предыдущем случае). Рассмотрим пример письма, отправленного в трех форматах:

 From: "John Coggeshall" 
To: Joe Users 
Subject: Hello from John!
Date: Wed, 20 Jun 2001 20:18:47 -0400
Message-ID: <000d01c0f9e7$bee1bb00$8a22f340@oemcomputer>
MIME-Version: 1.0
Content-Type: multipart/alternative; 
boundary="ZEND-12345";
Content-Transfer-Encoding: 7bit
This part of the E-mail should never be seen. If
you are reading this, consider upgrading your e-mail
client to a MIME-compatible client.
--ZEND-12345
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
 Hello! Here's that Zend.com!
-John
--ZEND-12345
Content-Type: text/enriched
Hello! Here is thatblueZend.com!
-John
--ZEND-12345
Content-Type: application/x-myapplication
Content-Transfer-Encoding: base64

--ZEND-12345--

В приведенном письме содержатся три фрагмента. Первый их них содержит данные text/plain для отображения письма в виде текста. Второй фрагмент содержит те же данные в формате text/enriched (если Вы хотите узнать подробней о формате, обратитесь к RFC 1896). Третий фрагмент содержит некий произвольный формат application/x-myapplication с base64 содержимым письма. Согласно с установленным заголовком multipart/alternative адресат увидит ту часть письма, которую его почтовый агент сможет отобразить визуально наилучшим образом. Это означает, что если пользователь имеет приложение, способное отобразить тип документа application/x-myapplication, тогда именно этот фрагмент будет показан пользователю. В противном случае будет произведена попытка отобразить тип text/enriched. И в случае неудачи будет отображена секция, содержащая письмо в формате text/plain.

Не случайно самый примитивный способ отображения письма был поставлен первым. Это сделано с учетом того, что почтовый клиент пользователя может не поддерживать формат MIME.

Очевидно, что заголовок multipart/alternative предоставляет возможность отправлять письма в формате text/plain и text/html одновременно, например:

 From: "John Coggeshall" 
To: Joe Users 
Subject: Hello from John!
Date: Wed, 20 Jun 2001 20:18:47 -0400
Message-ID: <000d01c0f9e7$bee1bb00$8a22f340@oemcomputer>
MIME-Version: 1.0
Content-Type: multipart/alternative; 
boundary="ZEND-12345";
Content-Transfer-Encoding: 7bit
This part of the E-mail should never be seen. If
you are reading this, consider upgrading your e-mail
client to a MIME-compatible client.
--ZEND-12345
Content-Type: text / plain; charset = "iso-8859-1"
Content-Transfer-Encoding: 7bit
Hey joe
I heard you want to know where you want to know. Here's the address:
/zend/spotlight/index.php
-John
--ZEND-12345
Content-Type: text / html
Content-Transfer-Encoding: 7bit
Hey joe
I heard you wanted 
   Zend's  website. 
Here's the address: 
   Code Gallery 
-John
--ZEND-12345--

And finally, a few words about sending emails with embedded images. There are several ways to implement this feature. In the section containing the HTML code, you can write the following: Sending mail using PHP in linux or windows. If at the time of opening such a letter, the user is in on-line and this action is not prohibited by the settings of his email client, the contents of the picture will be requested from the server and it will be displayed. The advantage of this method is the small size of the sent letter. The downside is the need for on-line availability and dependence on email client settings. The second way is to use the Content-ID header. It is used to map each section of a unique identifier letter. In general, such a header can be specified for each section of the letter, but in practice it only makes sense if you need to refer to this fragment in the body of the letter or in other fragments. An example would be pictures, flash-animations, videos. And thus, you get the opportunity to refer not to an external source,and to the section of the letter by its identifier. In a section it looks like this:

 From: "John Coggeshall" 
To: Joe Users 
Subject: Hello from John!
Date: Wed, 20 Jun 2001 20:18:47 -0400
Message-ID: <000d01c0f9e7$bee1bb00$8a22f340@oemcomputer>
MIME-Version: 1.0
Content-Type: multipart/alternative; 
boundary="ZEND-12345";
Content-Transfer-Encoding: 7bit
This part of the E-mail should never be seen. If
you are reading this, consider upgrading your e-mail
client to a MIME-compatible client.
--ZEND-12345
Content-Type: text/html
Content-Transfer-Encoding: 7bit
This is the zend logo:
Sending mail using PHP in linux or windows
--ZEND-12345
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
Content-ID: ZendImage12345

--ZEND-12345--

Новизна этого примера в строке Sending mail using PHP in linux or windows , где внешний источник был заменен указанием локального идентификатора. Фактическое значение, указываемое в заголовке Content-ID, может быть произвольно, как и в случае с boundary. Главное требование - его уникальность в переделах письма. Используя такую методику прикрепления файлов, Вы можете комплектовать полноценный пакет документов, таких, как html-содержимое письма, файлы стилей, картинки, офисные документы, текстовая версия, и отправлять его одним письмом. Правда, при этом не стоит забывать, что большинство пользователей имеют канал с малой пропускной способностью и, скорее всего, просто не захотят получать письмо большого размера.

7. Примеры исходных кодов

7.1 Отправка писем с вложениями

function XMail( $from, $to, $subj, $text, $filename) {
$f = fopen($filename,"rb");
$un = strtoupper(uniqid(time()));
$head = "From: $from\n";
$head .= "To: $to\n";
$head .= "Subject: $subj\n";
$head .= "X-Mailer: PHPMail Tool\n";
$head .= "Reply-To: $from\n";
$head .= "Mime-Version: 1.0\n";
$head .= "Content-Type:multipart/mixed;";
$head .= "boundary=\"----------".$un."\"\n\n";
$zag = "------------".$un."\nContent-Type:text/html;\n";
$zag .= "Content-Transfer-Encoding: 8bit\n\n$text\n\n";
$zag .= "------------".$un."\n";
$zag .= "Content-Type: application/octet-stream;";
$zag .= "name=\"".basename($filename)."\"\n";
$zag .= "Content-Transfer-Encoding:base64\n";
$zag .= "Content-Disposition:attachment;";
$zag .= "filename=\"".basename($filename)."\"\n\n";
$zag .= chunk_split(base64_encode(fread($f,filesize($filename))))."\n";

return @mail("$to", "$subj", $zag, $head);
}
?>

Here are links to some of the more “advanced” classes:

  • http://renoir.vill.edu/~ylee/mailfile.txt
  • http://irbp.ru/mime_mail-imgs.html
  • http://php.spb.ru/php/mail.html

7.2 Using Sockets

function socketmail($server, $to, $from, $subject, $message) {
$connect = fsockopen ($server, 25, $errno, $errstr, 30);
fputs($connect, "HELO localhost\r\n");
fputs($connect, "MAIL FROM: $from\n");
fputs($connect, "RCPT TO: $to\n");
fputs($connect, "DATA\r\n");
fputs($connect, "Content-Type: text/plain; charset=iso-8859-1\n");
fputs($connect, "To: $to\n");
fputs($connect, "Subject: $subject\n");
fputs($connect, "\n\n");
fputs($connect, stripslashes($message)." \r\n");
fputs($connect, ".\r\n");
fputs($connect, "RSET\r\n");
}
?>

7.3 Using sendmail

$sendmail = "/usr/sbin/sendmail -t -f $sender -C /etc/sendmail.orig.cf";
$fd = popen($sendmail, "w");
fputs($fd, "To: recipient@example.com\r\n");
fputs($fd, "From: \"Sender Name\" <$sender>\r\n");
fputs($fd, "Subject: Finally\r\n");
fputs($fd, "X-Mailer: Mailer Name\r\n\r\n");
fputs($fd, $body);
pclose($fd);
?>

7.3 Using ActiveX

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

@$CDONTS->From = "from_user@domain.com";
@$CDONTS->To = "to_user@domain.com";
@$CDONTS->CC = "cc_user@domain.com";
@$CDONTS->BCC = "bcc_user@domain.com";

@$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();
?>

Or even

$objApp = new COM("Outlook.Application");
$myItem = $objApp->CreateItem(olMailItem);
$a=$myItem->Recipients->Add("admin@purplerain.org");
$myItem->Subject="Subject";
$myItem->Body="This is a Body Section now.....!";
$myItem->Display();
$myItem->Send();
?>


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)