LoginSignup
0
0

More than 5 years have passed since last update.

djangoでsettingsに書いているEMAIL_HOST_USER以外のユーザーでメールを送信する

Posted at

send_mailを使う。

from django.core.mail import send_mail

send_mail(subject, message, from, [to], fail_silently=False, auth_user=ANOTHER_HOST_USER, auth_password=ANOTHER_HOST_PASSWORD)

ただこれだとToでしか送れない。

BCCで送りたいんじゃ〜〜。

EmailMessageクラスを利用

send_mail()もEmailMessageクラスに軽くラッパをかぶせたもの。

from django.core.mail import EmailMessage

email = EmailMessage(subject, message, from, [to], [bcc])
email.send(fail_silently=False)

BCCで送信できた!!
ただ、こうすると、settingsのEMAIL_HOST_USERで送ることになる。

connectionを手動で開く

通常send_mail()のときはsendするときに勝手に開いてくれるけど、自分で開くようにする。

from django.core.mail import EmailMessage, get_connection

connection = get_connection(fail_silently=False, username=ANOTHER_HOST_USER, password=ANOTHER_HOST_PASSWORD)
connection.open()
email = EmailMessage(subject, message, from, [to], [bcc], connection=connection)
email.send()
# 複数送りたい場合
# connection.send_messages([email])
# 手動で開いたため閉じるのも手動
connection.close()

とするとsettingsに書いてあるユーザー以外のユーザーで宛先BCCのメールを送信できた!

まちがえてない?あってる???

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0