Skip to content

Unable to attach files to email using code from docs #218

@RandomJo

Description

@RandomJo

Expected behaviour

I expect to be be able to attach uploaded files to an email as I could with previous versions of wagtailstreamforms.

Actual behaviour

After upgrading to wagtailstreamforms==4.0.4, I get the following error when using the code in the docs to attach to an email. The code in the docs was working in wagtailstreamforms==3.21

Traceback (most recent call last):
  File "[PATH_TO_ENV]/lib/python3.8/site-packages/django/core/handlers/exception.py", line 56, in inner
    response = get_response(request)
  File "[PATH_TO_ENV]/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "[PATH_TO_ENV]/lib/python3.8/site-packages/wagtail/views.py", line 24, in serve
    result = fn(page, request, args, kwargs)
  File "[PATH_TO_PROJECT]/custom_forms/wagtailstreamforms_hooks.py", line 46, in process_form
    form_def.process_form_submission(form)
  File "[PATH_TO_ENV]/lib/python3.8/site-packages/wagtailstreamforms/models/form.py", line 184, in process_form_submission
    fn(self, form)
  File "[PATH_TO_PROJECT]//custom_forms/wagtailstreamforms_hooks.py", line 137, in email_submission
    file.open()
  File "[PATH_TO_ENV]/lib/python3.8/site-packages/django/core/files/uploadedfile.py", line 115, in open
    self.file.seek(0)
ValueError: I/O operation on closed file.

Here's my code:

 # create the email message
    email = EmailMessage(
        subject=subject,
        body=content,
        from_email=from_address,
        to=addresses,
    )

    # attach any files submitted
    for field in form.files:
        print(form.files.getlist(field))
        for file in form.files.getlist(field):
            print(file)
            print(file.__dict__)
            file.seek(0)
            email.attach(file.name, file.read(), file.content_type)

    # finally send the email
    email.send(fail_silently=True)

Steps to reproduce the behaviour

  1. Create a stream form with a file upload field (single or multiple).
  2. Add the form to a page.
  3. View the form on the site.
  4. Upload a file (any file type) and submit.
  5. You should see the error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions