Email form with attachment

Hi all,

It’s my first post on this forum and I am relatively new to Django, so my question my be a bit basic for you.

I want to build a contact form that sends an email with attachment to an email address that’s configured in settings.py. The form that I built so far (in forms.py and without attachment field) works fine.

I’m just struggling to make a field for an uploaded cv that will be sent as a file attached to the email. As far as I can see this is only possible if I have a modelform, but I have a regular django form.

I would be grateful to be pointed towards useful documentation on this topic or receive some advice.
Thanks,
Andres

Hi, to handle the file upload you can use a FileField in your form (see File Uploads | Django documentation | Django).

This wil give you an UploadedFile object in the_form.cleaned_data["the_file_field"].

Then, you can attach it to your email using EmailMessage(..., attachments=[(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type)])
or the_email.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type) (see Sending email | Django documentation | Django)

Many thanks for your explanation Antoine. I’ll try to implement your solution soon.