Skip to content

Instantly share code, notes, and snippets.

@nrobinaubertin
Created April 2, 2024 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrobinaubertin/53ca8670a56c4329160acf03fe9157a6 to your computer and use it in GitHub Desktop.
Save nrobinaubertin/53ca8670a56c4329160acf03fe9157a6 to your computer and use it in GitHub Desktop.
test script for emails sending
#!/usr/bin/env python3
import socket
import sys
from smtplib import SMTP, SMTPAuthenticationError, SMTPException, SMTP_SSL
smtp_address = "smtp-services.example.com"
# smtp_address = "service.smtp.example.com"
smtp_authentication = "login"
smtp_domain = "example.com"
smtp_password = "password"
smtp_port = 465
smtp_username = "username"
test_recipient = "example@example.com"
test_sender = "noreply@example.com"
connection_timeout = 5
communication_timeout = 5
if __name__ == "__main__":
try:
try:
smtp = SMTP_SSL(smtp_address, smtp_port, timeout=connection_timeout)
print("SMTP server reachable: OK")
except socket.timeout:
sys.exit("Connection timeout. Unable to connect to the SMTP server.")
except Exception as e:
print(f"An error occurred while trying to reach the SMTP server: {e}")
with smtp:
try:
print(smtp.noop())
print("Connection to SMTP server: OK")
smtp.timeout = communication_timeout
# smtp.starttls() # comment that out if the SMTP server doesn't support starttls
smtp.login(smtp_username, smtp_password)
message = (
f"From: {test_sender}\n"
f"To: {test_recipient}\n"
"Subject: SMTP Test Email\n"
"\nThis is a test email sent from the SMTP testing script."
)
smtp.sendmail(test_sender, test_recipient, message)
print("Test email sent successfully!")
except SMTPAuthenticationError:
print("SMTP authentication error. Please check your username/password.")
except SMTPException as e:
print(f"SMTP error occurred: {e}")
# "Sender address rejected: not owned by user" => incorrect test_sender
# "Sender address rejected: Domain not found" =>
except socket.timeout:
print("Communication timeout.")
except Exception as e:
print(f"An error occurred: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment