Shin さん:
例えばメールアドレスの入力ミスがあった場合は、送信元アドレスへMail Delivery Subsystemより、Delivery Status Notification (Failure)という通知がきますが、相手先の受信サーバへメールを届けようとした際に何かエラーが発生したかどうかは、このNotificationのみによって感知できるということでしょうか?
私:
はい、その通りです。
smtp.send_message()
を実行する際に発生する可能性のある smtplib.SMTPException
を例外処理(try ~ except
)で検出します。
import sys
from datetime import datetime
message = EmailMessage()
message['Subject'] = 'タイトル'
message['From'] = EMAIL_ADDRESS
# 同じメッセージ本文であればここで定義してもよいはず
message.set_content('メッセージ本文')
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
#smtp.set_debuglevel(True)
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
for row in reader:
message['To'] = row[0]
status = 'success'
try:
smtp.send_message(message)
except smtplib.SMTPException:
status = 'failure'
finally:
now = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
print(f'{now} Email to {message["To"]} status: {status}', file=sys.stderr)
del message['To']
例えば質問文にある error@gmail.com
に送信してみると、
2021/09/09 09:39:05 Email to error@gmail.com status: success
と表示されますが、この後に Mail From
(もしくは Return-Path
)に設定したメールアドレスに以下の様なメールが届きます。
Subject: Delivery Status Notification (Failure)
Auto-Submitted: auto-replied
** アドレス不明 **
アドレスが見つからなかったか、メールを受信できないアドレスであるため、メールは error@gmail.com に配信されませんでした。
詳細: https://support.google.com/mail/?p=NoSuchUser
応答:
550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/?p=NoSuchUser
error@gmail.com
に送信した場合の SMTP サーバとのやり取りは以下になります(必要な部分だけを抜き出して記載しています)。
send: mail FROM:<...> size=212
reply: 250 2.1.0 OK
send: rcpt TO:<error@gmail.com>
reply: 250 2.1.5 OK
send: data
reply: 354 Go ahead
send: Content-Type: text/plain; charset="utf-8" ...
reply: 250 2.0.0 OK 1631147944
# これは前述の Python スクリプトが表示しています
2021/09/09 09:39:05 Email to error@gmail.com status: success
send: QUIT
reply: 221 2.0.0 closing connection
それでは SMTPException
が発生するのはどの様な場合かと言えば、例えばメールアドレスが非正規な形式になっている場合です。一例としてドメイン名を指定しないアドレス宛に送信してみます。
メールアドレス error
宛に送信
send: mail FROM:<...> size=202
reply: 250 2.1.0 OK
send: rcpt TO:<error>
reply: 553 5.1.3 The recipient address <error> is not a valid RFC-5321 address.
send: rset
reply: 250 2.1.5 Flushed
2021/09/09 09:56:46 Email to error status: failure
send: QUIT
reply: 221 2.0.0 closing connection
まぁ、後から届く Delivery Status Notification (Failure)
のメールを自動的にチェックして…などという事も考えられなくはないですが、面倒ではありますね。。。
SMTP.set_debuglevel()
の結果の読み方が分からない、あたりではないでしょうか。