0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python でメール送信

Posted at

Python から SMTP サーバを使用してメールを送信するコードを書いたので、メモ。

SMTP サーバのログイン情報

SMTP_HOST = "example.com"
SMTP_USERNAME = "user@example.com"
SMTP_PASSWORD = "********"

メッセージの組み立て

メッセージオブジェクトは email.message.Message であれば何でも良いが、EmailMessage を使用すると何かと便利。

from email.message import EmailMessage

msg = EmailMessage()
msg["Subject"] = "テスト subject"
msg["From"] = SMTP_USERNAME
msg["To"] = "example@gmail.com"
msg.set_content("テスト body")

メッセージを送信する

送信する際の暗号化通信の方式として STARTTLS が利用できればいいが、できない場合は SMTPS を利用する。

STARTTLS を利用する場合

SMTP で暗号化通信をするには STARTTLS を利用する方法がベストプラクティスらしい。

from smtplib import SMTP

with SMTP(SMTP_HOST) as smtp:
    smtp.starttls()
    smtp.login(SMTP_USERNAME, SMTP_PASSWORD)
    smtp.send_message(msg)

ここではポート番号を指定していないのでデフォルトの 25 が使用されるが、場合によってはサブミッションポート (587) を指定する必要があるかもしれない。

SMTPS (SMTP over TLS) を利用する場合

何らかの事情で STARTTLS による暗号化通信を利用できない場合に SMTPS (SMTP over TLS) を利用することもできる。

from smtplib import SMTP_SSL

with SMTP_SSL(SMTP_HOST) as smtp:
    smtp.login(SMTP_USERNAME, SMTP_PASSWORD)
    smtp.send_message(msg)

この場合、デフォルトではポート 465 が使用される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?