Sending an HTML wit Attachment Mail using PHP Tutorial

In this tutorial, you will learn how to Send an HTML with an Attachment Mail using PHP Language without using PHP Libraries/Plugins. The main purpose of the tutorial is to provide a reference for IT/CS Students or new programmers to enhance their programming knowledge using the PHP Mail Function. Here, snippets are provided and a sample source code file that demonstrates the objective of this tutorial is free to download.

What is PHP mail() (Mail Function)?

PHP comes with mail() (mail function) which is used for sending mails from PHP Script. This function helps the developer provide their end-users with a way to notify them. It is commonly used for sending notifications, newsletters, and verification codes.

How to Send an HTML and Attachment Mail using PHP mail()?

Using the Content-Type: multipart/mixed mail header, we can create a PHP Script that will allow sending mail that contains HTML content with an Attachment.

Below are the sample snippets of a simple web application that demonstrate this tutorial's objective.

Setup Sendmail in XAMPP

For those who are using XAMPP, here are the following steps for the mailing setup using Google's SMTP.

  1. Open your XAMPP's php.ini file and follow the image below. File Path (xampp/php)

    XAMPP Mail Setup - PHP.INI

  2. Open your XAMPP's sendmail.ini file and follow the image below. File Path (xampp/sendmail)

    XAMPP Mail Setup - PHP.INI

Interface

Here is the sample snippet for the sample web application's page interface. The page contains a simple mailing form that contains the relevant input fields for sending mail. The snippet uses CDNs for loading the external libraries (Bootstrap, jQuery, and Summernote) which means an internet connection is a must while using the script to run it properly.

index.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Send Mail with Attachement | PHP</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.  
  9. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-lite.min.css" integrity="sha512-ZbehZMIlGA8CTIOtdE+M81uj3mrcgyrh6ZFeG33A4FHECakGrOsTPlPQ8ijjLkxgImrdmSVUHn1j+ApjodYZow==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  10.  
  11. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  12. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  13.  
  14. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  15. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  16. <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-lite.min.js" integrity="sha512-lVkQNgKabKsM1DA/qbhJRFQU8TuwkLF2vSN3iU/c7+iayKs08Y8GXqfFxxTZr1IcpMovXnf2N/ZZoMgmZep1YQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  17. html, body{
  18. min-height:100%;
  19. width:100%;
  20. }
  21. .table-holder{
  22. width:100%;
  23. max-height:65vh;
  24. overflow:auto;
  25. }
  26. .table>thead{
  27. position:sticky;
  28. top:0;
  29. background:white;
  30. z-index: 1;
  31. }
  32. </style>
  33. </head>
  34. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  35. <div class="container">
  36. <a class="navbar-brand" href="./">Sending Mail</a>
  37. <div>
  38. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  39. </div>
  40. </div>
  41. </nav>
  42. <div class="container-fluid px-5 my-3" id="SampleApp">
  43. <div class="col-lg-6 col-md-10 col-sm-12 mx-auto">
  44. <h3 class="text-center"><b>Sending Mail with Attachment using PHP</b></h3>
  45. <div class="d-flex w-100 justify-content-center">
  46. <hr class="w-50">
  47. </div>
  48.  
  49. </div>
  50. <div class="col-lg-8 col-md-10 col-sm-12 mx-auto">
  51. <div class="card rounded-0 shadow" id="dataSheetCard">
  52. <div class="card-header rounded-0">
  53. <div class="d-flex w-100 justify-content-between">
  54. <div class="col-auto flex-shrink-1 flex-grow-1">
  55. <div class="card-title">Mail Form</div>
  56. </div>
  57.  
  58. </div>
  59. </div>
  60. <div class="card-body rounded-0">
  61. <div class="container-fluid">
  62. <form action="sendMail.php" method="POST" enctype="multipart/form-data" id="mail-form">
  63. <div class="mb-3">
  64. <label for="recepient" class="form-label">Recepient Email</label>
  65. <input type="email" name="recepient" id="recepient" class="form-control form-control-sm rounded-0" required>
  66. </div>
  67. <div class="mb-3">
  68. <label for="subject" class="form-label">Subject</label>
  69. <input type="text" name="subject" id="subject" class="form-control form-control-sm rounded-0" required>
  70. </div>
  71. <div class="mb-3">
  72. <label for="message" class="form-label">Message</label>
  73. <textarea rows="5" name="message" id="message" class="form-control form-control-sm rounded-0" required></textarea>
  74. </div>
  75. <div class="mb-3">
  76. <label for="attach_file" class="form-label">Attachment</label>
  77. <input class="form-control form-control-sm rounded-0" id="attach_file" name="attach_file" type="file" required>
  78. </div>
  79. <div class="mb-3">
  80. <div class="d-grid">
  81. <button class="btn btn-primary rounded-pill">Send Mail</button>
  82. </div>
  83. </div>
  84. </form>
  85. </div>
  86. </div>
  87. </div>
  88. </div>
  89. </div>
  90. <script src="app.js"></script>
  91. </body>
  92. </html>

JavaScript

The following snippet is a JavaScript file for initiating the HTML Text Editor into the mail message text area. The script requires the Summernote Library. You can also use your preferred input text editor.

app.php

  1. $(document).ready(function(){
  2. $('#message').summernote({
  3. height:"20vh",
  4. toolbar: [
  5. ['style', ['bold', 'italic', 'underline', 'clear']],
  6. ['font', ['strikethrough', 'superscript', 'subscript']],
  7. ['fontsize', ['fontsize']],
  8. ['color', ['color']],
  9. ['para', ['ul', 'ol', 'paragraph']],
  10. ['height', ['height']]
  11. ]
  12. })
  13. })

PHP Script

Here is the PHP snippet that contains the PHP Script for sending an email using the data filled from the mail form. The script requires a POST Method request in order to process the mail using the required Post Data.

sendMail.php

  1. <?php
  2.  
  3. if($_SERVER['REQUEST_METHOD'] == "POST"){
  4.  
  5. $subject = $_POST['subject'];
  6. $recepient = $_POST['recepient'];
  7. $message = "<html><body>".$_POST['message']."</body></html>";
  8.  
  9.  
  10.  
  11.  
  12.  
  13. $file_dir = "uploads/";
  14. if(!dir($file_dir)){
  15. mkdir($file_dir);
  16. }
  17. if(isset($_FILES['attach_file']['tmp_name']) && !empty($_FILES['attach_file']['tmp_name'])){
  18. $file_name = ($_FILES['attach_file']['name']);
  19.  
  20. /**
  21.   * Check filename if has duplicate
  22.   */
  23. $i = 0;
  24. while(true){
  25. $path = pathinfo($file_name);
  26. $tmp_name = $path['filename'].($i > 0 ? "_$i" : "").".".$path['extension'];
  27. if(is_file($file_dir.$tmp_name)){
  28. $i++;
  29. }else{
  30. $file_name = $tmp_name;
  31. break;
  32. }
  33. }
  34.  
  35. $upload = move_uploaded_file($_FILES['attach_file']['tmp_name'], $file_dir.$file_name);
  36. if($upload){
  37. $file_path = $file_dir.$file_name;
  38.  
  39.  
  40. /**
  41.   * Sending Mail
  42.   */
  43.  
  44.  
  45. //File to attach on mail
  46. $attached_content = file_get_contents($file_path);
  47. $attached_content = chunk_split(base64_encode($attached_content));
  48.  
  49. // a random hash will be necessary to send mixed content
  50. $separator = md5(time());
  51.  
  52. $eol = "\r\n";
  53.  
  54. // Mail Main Header
  55. $headers = "From: Sample Mail with Attachment <[email protected]>" . $eol;
  56. $headers .= "MIME-Version: 1.0" . $eol;
  57. $headers .= "Content-Type: multipart/alternative; boundary=\"" . $separator . "\"" . $eol;
  58. $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
  59.  
  60. // HTML Message
  61. $body = "--" . $separator . $eol;
  62. $body .= "MIME-Version: 1.0" . $eol;
  63. $body .= "Content-Type: text/html;charset=UTF-8" . $eol;
  64. $body .= "Content-Transfer-Encoding: 8bit" . $eol;
  65. $body .= $eol. ($message) . $eol . $eol;
  66.  
  67. // Attachment
  68. $body .= "--" . $separator . $eol;
  69. $body .= "Content-Type: application/octet-stream; name=\"" . ($file_name) . "\"" . $eol;
  70. $body .= "Content-Transfer-Encoding: base64" . $eol;
  71. $body .= "Content-Disposition: attachment" . $eol;
  72. $body .= $attached_content . $eol;
  73. $body .= "--" . $separator . "--";
  74.  
  75. try{
  76. // Sending mail
  77. mail($recepient, $subject, $body, $headers);
  78. echo "<script>alert('Mail has been sent successfully!'); location.replace('./');</script>";
  79. } catch (Exceptions $err){
  80. print_r($err);
  81. }
  82.  
  83. }else{
  84. echo "<script>alert('Uploading File Failed!'); location.replace(document.referrer);</script>";
  85. }
  86. }else{
  87. echo "<script>alert('File Attachment is required!'); location.replace(document.referrer);</script>";
  88. }
  89.  
  90. }
  91.  
  92. ?>

Snapshots

Here are the snapshots of the result of the snippet that I provided above.

Mailing Form Page

Sending an HTML with Attachement Mail using PHP

Sample Sent Mail Output

Sending an HTML with Attachement Mail using PHP

That's it. I have also provided the complete source code zip file that I created for this tutorial. You can download it by clicking the Download Button below this article.

That's the end of this tutorial. I hope this Sending an HTML with Attachment Mail using PHP Tutorial helps you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding:)

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
5 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.