Skip to content

Commit

Permalink
Merge pull request #124 from collective/quang/add_email_xml_attachment
Browse files Browse the repository at this point in the history
Add option to attachment form data in XML format to email
  • Loading branch information
tkimnguyen committed Sep 1, 2018
2 parents 7aedf7f + 5d3d3a8 commit 55bbc41
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 3 deletions.
3 changes: 2 additions & 1 deletion CHANGES.rst
Expand Up @@ -4,7 +4,8 @@ Changelog
2.0.0b7 (unreleased)
--------------------

- Nothing changed yet.
- Add option to attach form data in XML format to email
[nngu6036]


2.0.0b6 (2018-08-20)
Expand Down
30 changes: 29 additions & 1 deletion src/collective/easyform/actions.py
Expand Up @@ -30,8 +30,10 @@
from email.MIMEText import MIMEText
from email.utils import formataddr
from io import BytesIO
from json import dumps
from logging import getLogger
from plone import api
from plone.app.textfield.value import RichTextValue
from plone.autoform.view import WidgetsView
from plone.supermodel.exportimport import BaseHandler
from Products.CMFCore.utils import getToolByName
Expand All @@ -40,6 +42,7 @@
from Products.PythonScripts.PythonScript import PythonScript
from StringIO import StringIO
from time import time
from xml.etree import ElementTree as ET
from z3c.form.interfaces import DISPLAY_MODE
from zope.component import queryUtility
from zope.contenttype import guess_content_type
Expand Down Expand Up @@ -336,6 +339,16 @@ def get_header_info(self, fields, request, context,

return headerinfo

def serialize(self, field):
"""Serializa field to save to XML.
"""
if isinstance(field, set) or isinstance(field, list):
list_value = list([str(f) for f in field])
return dumps(list_value)
if isinstance(field, RichTextValue):
return field.raw
return str(field)

def get_attachments(self, fields, request):
"""Return all attachments uploaded in form.
"""
Expand All @@ -346,7 +359,9 @@ def get_attachments(self, fields, request):
sendCSV = getattr(self, 'sendCSV', None)
if sendCSV:
csvdata = []

sendXML = getattr(self, 'sendXML', None)
if sendXML:
xmlRoot = ET.Element("form")
for fname in fields:
field = fields[fname]
showFields = getattr(self, 'showFields', []) or []
Expand All @@ -356,6 +371,12 @@ def get_attachments(self, fields, request):
getattr(self, 'showAll', True) or fname in showFields):
csvdata.append(field)

if sendXML:
if not is_file_data(field) and (
getattr(self, 'showAll', True) or fname in showFields):
ET.SubElement(xmlRoot, "field", name=fname).text \
= self.serialize(field)

if is_file_data(field) and (
getattr(self, 'showAll', True) or fname in showFields):
data = field.data
Expand All @@ -371,6 +392,13 @@ def get_attachments(self, fields, request):
now = DateTime().ISO().replace(' ', '-').replace(':', '')
filename = 'formdata_{0}.csv'.format(now)
attachments.append((filename, 'text/plain', 'utf-8', csv))

if sendXML:
xmlstr = ET.tostring(xmlRoot, encoding='utf8', method='xml')
now = DateTime().ISO().replace(' ', '-').replace(':', '')
filename = 'formdata_{0}.xml'.format(now)
attachments.append((filename, 'text/xml', 'utf-8', xmlstr))

return attachments

def get_mail_text(self, fields, request, context):
Expand Down
13 changes: 12 additions & 1 deletion src/collective/easyform/interfaces/mailer.py
Expand Up @@ -130,7 +130,7 @@ class IMailer(IAction):
fieldset(u'message', label=PMF('Message'), fields=[
'msg_subject', 'subject_field', 'body_pre', 'body_post',
'body_footer', 'showAll', 'showFields', 'includeEmpties',
'sendCSV', ])
'sendCSV', 'sendXML'])
directives.read_permission(msg_subject=MODIFY_PORTAL_CONTENT)
msg_subject = zope.schema.TextLine(
title=_(u'label_formmailer_subject', default=u'Subject'),
Expand Down Expand Up @@ -244,6 +244,17 @@ class IMailer(IAction):
required=False,
)

directives.read_permission(sendXML=MODIFY_PORTAL_CONTENT)
sendXML = zope.schema.Bool(
title=_(u'label_sendXML_text', default=u'Send XML data attachment'),
description=_(u'help_sendXML_text', default=u''
u'Check this to send an XML file '
u'attachment containing the values '
u'filled out in the form.'),
default=False,
required=False,
)

fieldset(u'template', label=PMF(
'Template'), fields=['body_pt', 'body_type'])
directives.write_permission(body_pt=config.EDIT_TALES_PERMISSION)
Expand Down
17 changes: 17 additions & 0 deletions src/collective/easyform/tests/testMailer.py
Expand Up @@ -10,6 +10,7 @@
from collective.easyform.interfaces import IActionExtender
from collective.easyform.tests import base
from plone import api
from plone.app.textfield.value import RichTextValue
from plone.namedfile.file import NamedFile

import email
Expand Down Expand Up @@ -522,3 +523,19 @@ def test_custom_email_template(self):
mailer = get_actions(self.ff1)['mailer']
mailer.onSuccess({}, self.layer['request'])
self.assertIn(u'Custom e-mail template!', self.messageText)

def test_MailerXMLAttachments(self):
""" Test mailer with dummy_send """
mailer = get_actions(self.ff1)['mailer']
mailer.sendXML = True
mailer.sendCSV = False
fields = dict(
topic='test subject',
replyto='test@test.org',
comments='test comments',
choices=set(['A', 'B']),
richtext=RichTextValue(raw='Raw')
)
request = self.LoadRequestForm(**fields)
attachments = mailer.get_attachments(fields, request)
self.assertEqual(1, len(attachments))

0 comments on commit 55bbc41

Please sign in to comment.