Failure to add csrf token to response - PloneFormGen and custom mail script in Plone 5

I've created a custom mailer script for PloneFormGen, (what I have below is a rough example, my script does a lot more) because of this I couldn't use the built in mail adapter.

from Products.CMFCore.utils import getToolByName
mailhost = getToolByName(ploneformgen, 'MailHost')

import logging
logger = logging.getLogger("mailer-logger")

token_url =  "mysite.com/myurl"

message = ""

subject = "Hey Peeps"

sender = "info@mysiteexample.com"
recipient = request.form.get("replyto", None)

if recipient:
	mailhost.send(message, 
                                  recipient, 
                                  sender, 
                                  subject=subject, charset="utf-8")

When my form calls the script I get the following in the traceback:

   - <PythonScript at /Plone/myform/custom-mailer/custom-mailer>
   - Line 42
Unauthorized: You are not allowed to access 'send' in this context
2016-02-21 17:54:03 WARNING plone.protect error parsing dom, failure to add csrf token to response for url http://mysite:8081/Plone/myform/fg_base_view_p3

I think the plone.protect warning is simply what it is: a warning.

I suppose the real error is that you are probably trying this as anonymous user, and anonymous does not have the right permission. There are a few mail related permissions, I think 'Use mailhost services' is the one. It might be fine to give this permission to anonymous, at least to test if that fixes the immediate problem.

Alternatively, maybe you can override something in the standard PloneFormGen MailAdapter to get what you want.

Thanks for the feedback @mauritsvanrees will see if I can unravel it with those pointers.

I just ran into this myself with a Script (Python) that gives that error when I use the Test tab... and I can confirm that it is not just a warning: the content I'm trying to create isn't being created.

2017-06-20 14:01:19 WARNING plone.protect error parsing dom, failure to add csrf token to response for url http://localhost:8080/Castle/portal_skins/custom/content_filler