Django メールにファイルを添付する

Djangoのメール送信のメモ

デフォルトでSMTPによる送信が可能。settings.pyでのバックエンドの書き換えでコンソールに繋げられもする。

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

参考:DjangoからGmail経由でメール送信する際の手順 - 素数好きの最高技術責任者のブログ

参考リンクでgmailの設定をすれば、公式ドキュメントの

from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

で件名と本文の送信が可能になる。

ファイルの添付をメモとしてまとめておく。

個人的にはhtmlを添付したかったので、テンプレートを利用してレンダリングを行い、 その文字列を添付するという形にした。

from django.template.engine import Engine
from django.template import Context
from django.core.mail import EmailMessage

template = Engine.get_default().get_template('<AppName>/attachment.html')
html = template.render(Context({
    'title': '<Title>',
    'contents': [<Content>]
}))
mail = EmailMessage(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
)
# ファイル名の拡張子からmimeタイプを推測してくれる
mail.attach('<FileName>.html', html)
mail.send()

公式ドキュメントはこの辺り。

  • [The Django template language: for Python programmers Django documentation Django](https://docs.djangoproject.com/en/2.1/ref/templates/api/)
  • [Sending email Django documentation Django](https://docs.djangoproject.com/en/2.1/topics/email/)

Djangoの基礎は本でもいいと思う。

Python3 + Django2.0入門 - Pythonで作るWebアプリケーション開発入門 - その1

Python3 + Django2.0入門 - Pythonで作るWebアプリケーション開発入門 - その1

posted with amazlet at 18.11.30

(2018-08-19)
売り上げランキング: 2,321

Amazon.co.jpで詳細を見る