Hack 67 Send a Purchase Confirmation Email with IPN

figs/moderate.gif figs/hack67.gif

Automate communication with customers by sending simple order-confirmation emails.

In this hack, your web server uses IPN to learn about purchases a customer makes and sends the customer an email confirming her purchase. To use this hack, you need to have an environment that allows you to execute server-side scripts that can send email. This example uses Microsoft's Active Server Pages (ASP), but the concepts apply to any scripting language you choose.

Before using this example, set up and test the basic IPN script described in [Hack #65] . You'll add the code presented here to that basic script, giving your system the ability to send email messages to customers after each purchase.

All popular web scripting environments provide a tool for sending electronic mail. Microsoft Windows server environments, for example, have a Common Data Objects (CDO) mail component preinstalled. Regardless of the platform, the email messages require a subject, a message body, the recipient's address, and the sender's address. You can find the recipient's address and other information about the sale in the IPN posting, such as the payer_email variable:

Payer_email = Request.Form("payer_email")

7.7.1 The Code

Place this code in your IPN script after the IPN information has been verified. In PayPal's sample scripts, the following code should appear at the 'process payment comment:

'Get the customer's email address

Dim payer_email

Payer_email = Request.Form("payer_email")

'Get information about the purchase the customer made

Dim item_name, item_number

Item_name = Request.Form("item_name") 

Item_number = Request.Form("item_number")

'Create the body of the email

Dim mail_body

Mail_body = "Thank you for your order. Below are the details." & VbCrLf 

                & "Item Name: " & item_name & VbCrLf & "Item Number: " 

                & item_number & ""

'Create an email object and send the message

Dim MailCDO

Set MailCDO = Server.CreateObject("CDONTS.NewMail")

MailCDO.From = "sales@yoursite.com"

MailCDO.To = payer_email

MailCDO.Subject = "Order Information"

MailCDO.Body = mail_body

MailCDO.Send( )

Set MailCDO = Nothing

When your site makes a sale, the code is executed and an email is sent to the customer verifying her order information. Keeping your customer informed in this way is a good practice, because it assures the customer that she made the purchase she intended to, and builds your reputation as a responsive merchant.