AJAX mail service on Google App Engine

Setting up a mail service in the Google App Engine is simple enough following the tutorial on the Google Cloud Platform. I create a seperate class for the mail service like this:

import webapp2
from google.appengine.api import mail

class MailService(webapp2.RequestHandler):
  def post(self):
    mailFrom = self.request.get('mailFrom')
    mailMsg = self.request.get('mailMsg')
    if not mail.is_email_valid(mailFrom):
      self.response.write('wrong mail address')
      return
    message=mail.EmailMessage(
      sender='dennisargeomatica@gmail.com',
      subject='Mail from website')
    message.to='dbauszus@gmail.com'
    message.body=(
      'Mail from: %s \n'
      'Message: %s \n'
      %(mailFrom,mailMsg))
    message.send()
    message=mail.EmailMessage(
      sender='dennisargeomatica@gmail.com',
      subject='Your mail to Argeomatica')
    message.to=mailFrom
    message.body=(
      'Thank you, we have received your mail. \n'
      'Message: %s \n'
      %(mailMsg))
    message.send()
    self.response.write('mail sent')

app = webapp2.WSGIApplication(
  [('/mailService', MailService)],
  debug=True)

Coming from an ASP.net background I am used to work with update panels which allow me to do use a submit input control without the need of rendering the complete page after the submit.

The jinja2 framework, although incredibly fast, does not allow for a similar functionality. Instead we will use an AJAX call from the client to the GAE mail service.

Creating an AJAX call is dead simple with jQuery.ajax(). I call my GAE mail service from javaScript like so:

function mailService() {
  mailFrom = $('#tbFrom').val();
  mailMsg = $('#tbMail').val();
  $.ajax({
    type : 'POST',
    url : 'mailService',
    data : {
      mailFrom:mailFrom,
      mailMsg:mailMsg
      },
    success: function(response) {
      $('#mailStatus').html(response);
      }
    })
}

The function will grab the email address and message body from the DOM input elements and POST the data to the mail service. The success event handler will then receive confirmation of the process from the service and display the message on the page.

The complete site is hosted here.

The complete code is on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *