Monday, June 18, 2012

How to move beyond the App Engine free mail limitations

Appengine have very tough quota limits for sending mail to user (now it's about 100 recipients in day). It so small even for little apps. What you need to do for solve that kind of problem?
  1. Use you standalone server or VPS with installed php
  2. Create file mailgate.php which contain code below and upload file to you VPS.:
     $user_code  = $_POST['code'];
     if ($user_code != $MAILGATE_KEY) {echo("wrong pass");die();}
     $to   = $_POST['to'];
     $subject  = $_POST['subj'];
     $body   = $_POST['body'];
     $headers = 'From: MY NAME ' . "\r\n" .
     'Reply-To:' . "\r\n".
        'Content-type: text/plain; charset=utf-8' . "\r\n";
     if (mail($to, $subject, $body, $headers)) {echo("sent");} else {echo('error');die();}
  3. on server side create function for easy sending mail
    def sendmail(to, subject, body):
        mailqueue = taskqueue.Queue('mailqueue')
        task = taskqueue.Task(url='/queue/sendmail', params={
                                                    'subject': subject,
                                                    'to': to,
                                                    'body': body})
  4. create file queue.yaml for properly sending mail (appengine limit count of request per minutes)
    - name: mailqueue
      bucket_size: 1
      rate: 30/m
        task_age_limit: 2d
  5. Create entry point '/queue/sendmail':
    class SendEmail(webapp.RequestHandler):
        def post(self):
            data = {
                'to':  unicode(self.request.get('to')).encode('utf-8'), 
                'subj': unicode(self.request.get('subject')).encode('utf-8'),
                'body': unicode(self.request.get('body')).encode('utf-8'),
                'code': settings.MAILGATE_KEY
            data = urllib.urlencode(data)
            result = urlfetch.fetch(settings.MAILGATE_URL, deadline=55, payload = data, method = urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'})
  "Sending mail to " + self.request.get('to') + " " + result.content)
  6. Put in you file with definition for:
    • MAILGATE_URL (it's full URL where you you actual mailgate.php available)
    • MAILGATE_KEY (same as in mailgate.php)
  7. Use you custome sendmail instead of appengine default.
  8. Enjoy!

No comments:

Post a Comment