Email using PHP

Admin   PHP   484  2020-12-11 22:08:52

PHP must be configured correctly in the php.ini file with details about how your system sends emails. Open the available php.ini in /etc/ directory and look for the section that starts with [mail function].

Email using PHP

Windows users should make sure that there are 2 directives provided. The first one is called SMTP, which defines your email server address. The second is called sendmail_from, which defines your own email address.

The configuration for Windows looks like this:

[mail function]

; For Win32 only.

SMTP = smtp.secureserver.net


; For win32 only

sendmail_from = [email protected]

Linux users need to tell PHP the location of the sendmail application. The path must be specified for the sendmail_path directive.

The configuration for Linux looks like this:

[mail function]

; For Win32 only.

SMTP = 


; For win32 only

sendmail_from = 


; For Unix only

sendmail_path = /usr/sbin/sendmail -t -i

Now let's do the email sending using PHP.

Send simple text email in PHP

PHP uses the mail() function to send an email. This function requires 3 required parameters that specify the recipient's email address, the subject of the message, and the content of the message, in addition to two optional parameters.

mail(to, subject, message, headers, parameters);

The table below describes these parameters:

ParametersDescribe

Parameters Describe
big Obligatory. Indicates the email address of the recipient
subject Obligatory. Specify the subject of the email. This parameter cannot contain newline characters.
message Obligatory. Indicates the content of the message. Lines are separated by an LF (\ n). Each line must not exceed 70 characters
headers Optional. Defines additional headings, like From, Cc, and Bcc. Additional headers should be separated from a CRLF (\ r \ n)
parameters Optional. Specify an additional parameter for the mailing program

As soon as the mail function is called, PHP will send this email, then it will return true on success and false on failure.

To send mail to multiple recipients, the first parameter in the mail() function is the list of recipients separated by commas.

Send HTML email in PHP

When you send a text message using PHP, then all the content is treated as plain text. Even if you add HTML tags in a text message, it will display as regular text and the HTML tags will not be formatted with HTML syntax. However, PHP provides the option of sending the HTML message as an actual HTML message.

When sending an email message, you can specify a Mime version, content-type, and character set to send an HTML email.

For example

The following example sends an HTML email message to [email protected] copying it to [email protected] You can code this program in such a way that it will receive all of the content from the user and then it sends an email.

<html>

   

   <head>

      <title> Emailing in PHP </title>

   </head>

   

   <body>

      

      <?php

         $to = "[email protected]";

         $subject = "This is subject";

         

         $message = "<b> This is an HTML Message. </b>";

         $message. = "<h1> This is the headline. </h1>";

         

         $header = "From: [email protected] \ r \ n";

         $header = "Cc: [email protected] \ r \ n";

         $header. = "MIME-Version: 1.0 \ r \ n";

         $header. = "Content-type: text / html \ r \ n";

         

         $retval = mail($to, $subject, $message, $header);

         

         if ($retval == true){

            echo "Email is successful ...";

         }  else {

            echo "Could not send email ...";

         }

      ?>

      

   </body>

</html>

Send as email attachments in PHP

To send an email with mixed content it is necessary to set the Content-type header to multipart/mixed. Then text and attachment can be defined inside boundaries.

A boundary is started with 2 dashes followed by a unique number that cannot appear in the email message. PHP md5() function is used to generate a 32-digit hexadecimal number that's unique. A final boundary denoting the email's final section must also end with two hyphens.

<?php

   // The following variables are important and necessary

   $from = $_REQUEST["from"];

   $emaila = $_REQUEST["emaila"];

   $filea = $_REQUEST["filea"];

   

   if ($filea)

   {

      function mail_attachment($from, $to, $subject, $message, $attachment) {

         $fileatt = $attachment; // path to file

         $fileatt_type = "application/octet-stream"; // file type

         

         $start = strrpos($attachment, '/') == -1 ? strrpos($attachment, '//'): strrpos($attachment, '/') + 1;

         $fileatt_name = substr($attachment, $start, strlen($attachment)); // filename is used as attachment

         

         $email_from = $from; // address who sent this email

         $subject = "New Attachment";

$email_subject = $subject; // Subject part of the email

         $email_txt = $message; // the content of the email

         $email_to = $to; // recipient email address

         

         $headers = "From:". $email_from;

         $file = fopen($fileatt, 'rb');

         $data = fread($file, filesize ($fileatt));

         fclose($file);

         

         $msg_txt = "\ n \ n You have received a New Attachment from $from";

         $semi_rand = md5(time());

         $mime_boundary = "== Multipart_Boundary_x{$semi_rand} x";

         $headers. = "\ nMIME-Version: 1.0 \ n". "Content-Type: multipart / mixed; \ n". "boundary = \" {$ mime_boundary} \ "";

         

         $email_txt. = $msg_txt;

         $email_message. = "This is a multipart message in MIME format. \ n \ n". "- {$mime_boundary} \ n". "Content-Type: text / html; charset = \" iso-8859-1 \ "\ n". "Content-Transfer-Encoding: 7bit \ n \ n". $email_txt. "\ n \ n";

         $data = chunk_split (base64_encode($data));

         

         $email_message. = "- {$mime_boundary} \ n". "Content-Type: {$fileatt_type}; \ n". "name = \" {$fileatt_name} \ "\ n". // "Content-Disposition: attachment; \ n". // "filename = \" {$fileatt_name} \ "\ n". "Content-Transfer-Encoding: base64 \ n \ n". $data. "\ n \ n". "- {$mime_boundary} - \ n";

         $ok = mail($email_to, $email_subject, $email_message, $headers);

         

         if ($ok)

         {

            echo "File sent successfully.";

            unlink($attachment); // Delete the file after the attachment has been sent.

         }

         

         else

         {

            die ("Sorry for the email being sent. Please try again!");

         }

      }

      move_uploaded_file($_ FILES["filea"]["tmp_name"], 'temp/'. basename($_FILES['filea']['name']));

      mail_attachment("$from", "[email protected]", "subject", "message", ("temp/".$_FILES["filea"]["name"]));

   }

?>

<html>

   <head>

      

      <script language = "javascript" type = "text/javascript">

         function CheckData45()

         {

            with (document.filepost)

            {

               if (filea.value! = "")

               {

                  document.getElementById('one'). innerText = "Attaching File ... Please wait a moment !!!";

               }

            }

         }

      </script>

      

   </head>

   <body>

      

      <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">

         <tr>

            <td align="center">

               <form name="filepost" method="post" action="file.php" enctype="multipart / form-data" id = "file">

                  

                  <table width="300" border="0" cellspacing="0" cellpadding="0">

                     <tr valign="bottom">

                        <td height="20"> Your name: </td>

                     </tr>
<tr>

                        <td> <input name="from" type="text" id="from" size="30"> </td>

                     </tr>

                     

                     <tr valign="bottom">

                        <td height="20"> Your email address: </td>

                     </tr>

                     

                     <tr>

                        <td class="frmtxt2"> <input name="emaila" type="text" id="emaila" size="30"> </td>

                     </tr>

                     

                     <tr>

                        <td height="20" valign="bottom"> Attach File: </td>

                     </tr>

                     

                     <tr valign="bottom">

                        <td valign="bottom"> <input name="filea" type="file" id="filea" size="16"> </td>

                     </tr>

                     

                     <tr>

                        <td height="40" valign="middle"> <input name="Reset2" type="reset" id="Reset2" value="Reset">

                        <input name="Submit2" type="submit" value="Submit" onClick="return CheckData45()"> </td>

                     </tr>

                  </table>

                  

               </form>

               

               <center>

                  <table width="400">

                     <tr>

                        <td id="one">

                        </td>

                     </tr>

                  </table>

               </center>

               

            </td>

         </tr>

      </table>

      

   </body>

</html>