Ilya
Ilya

Reputation: 363

Sending emails to an email with an attachment

In the django function, I fill in a docx document template

doc = DocxTemplate('template.docx')

dates = date
prices = price

tbl_contents = [{'expirationdate': expirationdate, 'price': price}
                for expirationdate, price in zip(dates, prices)]

context = {
    'tbl_contents': tbl_contents,
    'finalprice': sum(prices),
    'startdate': startdate,
    'enddate': enddate
}

doc.render(context)
doc.save("static.docx")

How do I get a file static.docx and send it to email?

I sent ordinary emails via send_mail but how do I send emails with an attachment?

Upvotes: 0

Views: 310

Answers (1)

AFzal Saiyed
AFzal Saiyed

Reputation: 119

from io import BytesIO
from django.core.mail import EmailMessage


doc = DocxTemplate('template.docx')

dates = date
prices = price

tbl_contents = [{'expirationdate': expirationdate, 'price': price}
                for expirationdate, price in zip(dates, prices)]

context = {
    'tbl_contents': tbl_contents,
    'finalprice': sum(prices),
    'startdate': startdate,
    'enddate': enddate
}

doc.render(context)
file_io = BytesIO()
doc.save(file_io)


email = EmailMessage(subject="subject", body="mail Body", from_email="[email protected]", to=["[email protected]", "[email protected]"])
email.attach("static.docx", file_io.getvalue(), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
email.send()

Upvotes: 1

Related Questions