Send an email with an attachment django… here is a solution to the problem.
Send an email with an attachment django
I have a file URL in my database. I want to send the file as an email attachment. I tried the code below
def mail_business_plan(sender, instance, created, **kwargs):
if created:
ctx = {"ctx":instance}
from_email = 'info@some_email.in'
subject = 'Business Plan by' + instance.company_name
message = get_template('email/business_team.html').render(ctx)
to = ['[email protected]']
mail = EmailMessage(subject, message, to=to, from_email=from_email)
mail.attach_file(instance.presentation, instance.presentation.read(), instance.presentation.content_type)
return mail.send()
I get the error message “AttributeError: ‘FieldFile’ object does not have property ‘content_type'”
If the file path is stored in a database, what is the best way to send a message with an attachment.
Solution
Suppose you have a model
class MyModel(models. Model):
# other fields
presentation = models. FileField(upload_to='some/place/')
In your signal,
<b>import mimetypes</b>
def mail_business_plan(sender, instance, created, **kwargs):
if created:
ctx = {"ctx": instance}
from_email = 'info@some_email.in'
subject = 'Business Plan by' + instance.company_name
message = get_template('email/business_team.html').render(ctx)
to = ['[email protected]']
mail = EmailMessage(subject, message, to=to, from_email=from_email)
<b>content_type = mimetypes.guess_type(instance.presentation.name)[0] # change is here <<<</b>
mail.attach_file(instance.presentation, instance.presentation.read(),<b> content_type) # <<< change is here also</b>
return mail.send()
Quote:
mimetypes.guess_type()