'File from POST Request to MIMEBase
I'm currently trying to send mails with attachments.
However, I'm currently struggling to convert the file I'm supposed to receive.
Here's my request POST:
curl --form "[email protected]" http://localhost:8000/
I need to know how can I extract the file year.txt from my request, and then convert it to MIMEBase, so I can send it through EmailMessage.
file = request.POST.get('file')
email = EmailMessage(
subject,
content,
None,
['[email protected]'],
)
email.attach_file(file)
That'd be something like this; however, I'm not sure the process to follow. That's why I require your help.
Solution 1:[1]
EmailMessage does not support passing in the Subject etc. as arguments. Instead, you need something like
from email.message import EmailMessage
email = EmailMessage()
email["subject"] = subject
email["from"] = "[email protected]" # you need to pass in a sender too
email["to"] = "[email protected]"
email.set_content(content)
email.add_attachment(file, maintype="application", subtype="octet-stream")
If you have a more specific MIME type to use than the generic application/octet-stream, by all means use that instead. In this particular case, I guess text/plain would be correct and useful, but of course, that might not be applicable more generally, and really depends on your use case and application design.
See the examples from the email module documentation for variations and details.
Getting the generated message off your system is a separate topic which is often hard for beginners. If you run this in a place where you have an outgoing email server in the local network which doesn't require authentication, you should be able to simply create an smtplib.SMTP object and pass the message to its send_message method, but many real-world deployments have complications like requiring to authenticate to a remote server. There are, of course, many existing questions about that here, so please search before you ask a new question.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tripleee |
