Как я могу отправить сохраненный блоб по электронной почте в виде вложения? - PullRequest
0 голосов
/ 14 ноября 2018

Я отправляю pjd как блоб через javascript в django, а затем пытаюсь отправить его как вложение электронной почты.

Мой код:

def SendPrescriptionbyMail(request, cliniclabel, patient_id):
    from django.core.files.storage import default_storage
    print(request.FILES)
    print(request.FILES['file'])
    myform = forms.Form(request.POST, request.FILES)
    file = myform.files['file']
    print(file)
    file_name = default_storage.save(file.name, file)
    file = default_storage.open(file_name)
    print(f'file_name is {file_name}')
    file_url = default_storage.url(file_name)
    print(f'Or maybe {file_url}')
    recipient = 'joel@domain'
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    msg = MIMEMultipart()
    msg['Subject'] = "Your prescription"
    msg['From']    = "admin@me"
    msg['To']      = recipient
    msg.preamble = 'Your prescription is attached'
    msg.attach(MIMEText(file(file_name).read()))
    s = smtplib.SMTP('smtp.mailgun.org', 587)
    s.login('myid@somewhere', 'apikey')
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    s.quit()
    return HttpResponse('Successfully sent email')

Вывод:

<MultiValueDict: {'file': [<TemporaryUploadedFile: blob (application/pdf)>]}>
blob
blob
file_name is blob_4VZxpHY
Or maybe /data/blob_4VZxpHY
2018-11-14 19:02:36,554 django.request ERROR    Internal Server Error: /clinic/madhav/prescription/sendemail/patient/18
Traceback (most recent call last):
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joel/myappointments/clinic/views.py", line 4953, in SendPrescriptionbyMail
msg.attach(MIMEText(file(file_name).read()))
TypeError: 'File' object is not callable

1 Ответ

0 голосов
/ 14 ноября 2018

Просто выполните:

msg.attach(MIMEText(file.read()))
                        ^
                   removed (file_name)

Поскольку файл уже определен как файл с этим:

file = default_storage.open(file_name)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...