Как прикрепить файл, загруженный клиентом, к письму в Django?
Я пытаюсь сделать форму, в которую клиент может добавить файл и отправить его через страницу. Никакого сохранения файла в базе данных, просто прикрепить его и отправить на электронную почту компании. Вот детали
forms.py
class ContactForm(forms.Form):
name = forms.CharField(max_length=120, widget=forms.TextInput(attrs={'placeholder': 'Your name'}))
phone_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone number'}))
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'example@example.com'}))
customer_details = forms.FileField(required=False, widget=forms.ClearableFileInput(
attrs={'multiple': False, 'allow_empty_file': True}))
message = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Your message'}))
emailsender.py
from django.core.mail import send_mail
class EmailSender:
def __send_email(self, subject, message, recipient_list):
send_mail(
subject=subject,
message=message,
from_email=EMAIL_HOST_USER,
auth_password=EMAIL_HOST_PASSWORD,
recipient_list=recipient_list
)
def send_submitted_order(self, request, offers):
subject = f'Order {datetime.now().strftime("%Y-%m-%d %H:%M:%S.")}'
recipient_list = [RECIPIENT_EMAIL]
form = ContactForm(request.POST, request.FILES or None)
if form.is_valid():
customer_email = form.cleaned_data['email']
customer_phone = form.cleaned_data['phone_number']
customer_message = form.cleaned_data['message']
**customer_details = form.cleaned_data['customer_details']**
message = render_to_string(
'cart/message_for_company.html',
{'customer_message': customer_message, 'customer_email': customer_email,
'customer_phone': customer_phone, 'offers': offers}
)
self.__send_email(subject, message, recipient_list)
def send_message_to_customer(self, request, offers):
form = ContactForm(request.POST, request.FILES or None)
subject = f'Order {datetime.now().strftime("%Y-%m-%d %H:%M:%S.")}'
if form.is_valid():
customer_email = form.cleaned_data['email']
customer_phone = form.cleaned_data['phone_number']
customer_message = form.cleaned_data['message']
**customer_details = form.cleaned_data['customer_details']**
message = render_to_string(
'cart/message_for_customer.html',
{'customer_message': customer_message, 'customer_email': customer_email,
'customer_phone': customer_phone, 'offers': offers}
)
recipient_list = [customer_email]
self.__send_email(subject, message, recipient_list)
и минималистичный шаблон для render_to_string
<h1>Order</h1>
{% for offer in offers %}
{{ offer.name }} - {{ offer.quantity }}
{% endfor %}
{{ customer_message }}
{{ customer_phone }}
{{ customer_email }}
{{ customer_details }}
render_to_string не позволяет сделать вложение с помощью message.attach(company_details). Я прочитал всю документацию и другие подобные вопросы на SOF, но так и не смог разобраться.