RHEV Logo
Creating a Contact Form With Python On Google App Engine (GAE)

Creating a Contact Form With Python On Google App Engine (GAE)

There seems to be a bit of confusion surrounding this topic, and I myself ran into a few issues finding a consolidated solution without gathering information from several different resources. Before we get started, there is one crucial step that has to be taken, otherwise an error will be thrown upon submitting your contact form. Make sure you add an authorized sender. Dont worry, it’s quick and easy to do. After adding your authorized sender we’ll start with a simple contact form that includes fields for Name, Email, and Message (Details).

Create The Form

Create a file that will contain your form (we used contact.html). Paste the following snippet into said file.

<form action="send_mail" method="get"><div>
<input type="text" name="fullname" required>
<label>Full Name</label>
</div>
<div>
<input type="email" name="email" required>
<label>Email</label>
</div>
<div class="group">
<input type="text" name="details" required>
<label>Details</label>
</div>
<button type="submit">Send</button>
</form>

Now that we have our form created, we’ll add the following URL handler into our app.yaml file:

- url: /send_mail
  script: send_mail.app

Add The Mail Script

After creating your URL handler, create a python file named send_mail.py in the same directory that your app.yaml file resides in, and paste the following snippet of code into it:

from google.appengine.api import app_identity
from google.appengine.api import mail
import webapp2

class SendMessageHandler(webapp2.RequestHandler):
    def get(self):
        name = self.request.get["fullname"]
        email = self.request.get["email"]
        details = self.request.get["details"]
        message = mail.EmailMessage(
            sender="yourauthorized@sender.com",
            subject=str(name) + " has submitted a proposal.")

        message.to = "Your Name <your@email.com>"
        message.body = "Name:\n" + str(name) + "\n\nEmail:\n" + str(email) + "\n\nDetails:\n" + str(details)

        message.send()

app = webapp2.WSGIApplication([
    ('/send_mail', SendMessageHandler),
], debug=True)

Overview

You should be all set! The form itself won’t look pretty until you add some CSS styling to it, however this will get your emails coming in, and set you up to extend your form to meet your requirements.

All we’ve done here is perform three simple steps. When we created our form, we added an action (send_mail) which sends the input from the contact form to be handled (via our URL handler) by our script (send_mail.py).

Published by using 334 words.