DEV Community

David Kanekanian
David Kanekanian

Posted on

E5 - Email the Receipt

Once an order is confirmed, online shops commonly send an email receipt. First you must have email setup on your XAMPP installation, if not refer to Setting up email dispatch from a local server. If you haven't already, check out the previous tutorial stage where we saved orders in a database.

Open the file cart.php for editing in the following steps:

1. Replace your checkout link with a form element. Set the action to "on_checkout.php" and the method to post.

<form action="on_checkout.php" method="post"> </form>
Enter fullscreen mode Exit fullscreen mode

2. Add label and input elements inside the form for an email address field.

<div> <label>Email Address:</label> <input name="email"> </div>
Enter fullscreen mode Exit fullscreen mode

3. Add a button to ‘checkout’ or submit the form.

<button>Checkout</button>
Enter fullscreen mode Exit fullscreen mode

4. Test the new cart page by submitting an order. The result of the form is no different to the link from before, as nothing is being done with the customer’s email yet.

Open on_checkout.php for editing in the following steps:

5. Assign the submitted email address to a variable, underneath the database querying and above where the cart cookie is made to expire.

$emailAddress = $_POST["email"];
Enter fullscreen mode Exit fullscreen mode

6. Create variables for the email subject and headers. The subject will be the content sent as the subject and the headers will just have the email address you are sending from.

$emailSubject = "Invoice of your order from Neat Treats";
$emailHeaders = "From: neattreats.sender@gmail.com\r\n";
Enter fullscreen mode Exit fullscreen mode

7. Create a variable for the email body.

$emailBody = "Thanks for your order! We hope you enjoy it a lot.\n";
Enter fullscreen mode Exit fullscreen mode

8. Add a list of the products that were ordered to the email body using a foreach loop on the cart variable that was already created in this script when it was being saved into the database.

$emailBody .= "Products:\n";
foreach($cart as $productID => $quantity)
    $emailBody .= "Product #$productID x$quantity\n";
Enter fullscreen mode Exit fullscreen mode

9. Use the mail() function to send the invoice email to the customer.

mail($emailAddress, $emailSubject, $emailBody, $emailHeaders);
Enter fullscreen mode Exit fullscreen mode

10. Test out the updated checkout script by entering your personal email address. It will send you an email with the products you just ordered.

Parent topic: Example 5

Top comments (0)