I'm trying to catch all emails that bounced when sending them via smtplib in Python. I looked at this similar post which suggested adding an exception catcher, but I noticed that my sendmail
function doesn't throw any exceptions even for fake email addresses.
Here is my send_email
function which uses smtplib
.
def send_email(body, subject, recipients, sent_from="[email protected]"):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sent_from
msg['To'] = ", ".join(recipients)
s = smtplib.SMTP('mySmtpServer:Port')
try:
s.sendmail(msg['From'], recipients, msg.as_string())
except SMTPResponseException as e:
error_code = e.smtp_code
error_message = e.smtp_error
print("error_code: {}, error_message: {}".format(error_code, error_message))
s.quit()
Sample call:
send_email("Body-Test", "Subject-Test", ["[email protected]"], "[email protected]")
Since I set the sender as myself, I am able to receive the email bounce report in my sender's inbox:
<[email protected]>: Host or domain name not found. Name service error
for name=jfdlsaf.com type=A: Host not found
Final-Recipient: rfc822; [email protected]
Original-Recipient: rfc822;[email protected]
Action: failed
Status: 5.4.4
Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error
for name=jfdlsaf.com type=A: Host not found
Is there a way to get the bounce message through Python?