📜 ⬆️ ⬇️

Sending mail using PHP

While working on the project, I had to create a specific “application form” in which I had to send the entire form to the specified email address, and I immediately remembered the PHP mail () function.


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

Required parameters:

Optional parameters:

Return value:


Simplest example

 <?php mail("E-mail ", "", "  \n 1-  \n 2-  \n 3- "); ?> 


Let's move on to a more complex example.


 <?php $to = "<mail@example.com>, " ; $to .= "mail2@example.com>"; $subject = " "; $message = ' <p> </p> </br> <b>1-  </b> </br><i>2-  </i> </br>'; $headers = "Content-type: text/html; charset=windows-1251 \r\n"; $headers .= "From:    <from@example.com>\r\n"; $headers .= "Reply-To: reply-to@example.com\r\n"; mail($to, $subject, $message, $headers); ?> 

')
In the beginning, we determine to whom the letter is addressed, the & to variable is responsible for this, and if there are several recipients, then we write the comma separated email addresses. mail.

The variables $ subject and $ message, I will not describe, this is understandable.

In our example, the $ headers variable consists of 3 lines:


And now the most interesting is sending an attachment letter


 $subject = " "; $message =" "; //  ,     , , ,    .. $filename = "file.doc"; //   $filepath = "files/file.doc"; //   //      ,    $boundary = "--".md5(uniqid(time())); //   $mailheaders = "MIME-Version: 1.0;\r\n"; $mailheaders .="Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"; //       boundary $mailheaders .= "From: $user_email <$user_email>\r\n"; $mailheaders .= "Reply-To: $user_email\r\n"; $multipart = "--$boundary\r\n"; $multipart .= "Content-Type: text/html; charset=windows-1251\r\n"; $multipart .= "Content-Transfer-Encoding: base64\r\n"; $multipart .= \r\n; $multipart .= chunk_split(base64_encode(iconv("utf8", "windows-1251", $message))); //     //   $fp = fopen($filepath,"r"); if (!$fp) { print "   22"; exit(); } $file = fread($fp, filesize($filepath)); fclose($fp); //   $message_part = "\r\n--$boundary\r\n"; $message_part .= "Content-Type: application/octet-stream; name=\"$filename\"\r\n"; $message_part .= "Content-Transfer-Encoding: base64\r\n"; $message_part .= "Content-Disposition: attachment; filename=\"$filename\"\r\n"; $message_part .= \r\n; $message_part .= chunk_split(base64_encode($file)); $message_part .= "\r\n--$boundary--\r\n"; //    ,       $multipart .= $message_part; mail($to,$subject,$multipart,$mailheaders); //   //   60 . if (time_nanosleep(5, 0)) { unlink($filepath); } //   

Source: https://habr.com/ru/post/444744/


All Articles