Skip to content

Instantly share code, notes, and snippets.

@colkito
Last active June 25, 2024 18:44
Show Gist options
  • Save colkito/ec29b811f6d611042e32e6b1a650ac44 to your computer and use it in GitHub Desktop.
Save colkito/ec29b811f6d611042e32e6b1a650ac44 to your computer and use it in GitHub Desktop.
SMTP Tester
# Code generated by Claude 3.5 Sonnet, an AI assistant created by Anthropic.
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import Optional
def test_smtp_connection(
sendgrid_username: str,
sendgrid_password: str,
sender_email: str,
recipient_email: str,
subject: str = "SMTP Test",
body: str = "This is a test email sent using SendGrid.",
) -> Optional[str]:
"""
Test SMTP connection using SendGrid and send a test email.
This function establishes a secure SSL connection to SendGrid's SMTP server,
authenticates using the provided credentials, and sends a test email.
Args:
sendgrid_username (str): SendGrid username (typically "apikey").
sendgrid_password (str): SendGrid API key.
sender_email (str): Email address of the sender.
recipient_email (str): Email address of the recipient.
subject (str, optional): Subject of the test email. Defaults to "SMTP Test".
body (str, optional): Body of the test email. Defaults to a generic test message.
Returns:
Optional[str]: None if the email was sent successfully, or an error message if it failed.
Raises:
smtplib.SMTPException: If there's an error during the SMTP operation.
ssl.SSLError: If there's an SSL-related error.
"""
smtp_server = "smtp.sendgrid.net"
port = 465 # For SSL
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = recipient_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
context = ssl.create_default_context()
try:
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sendgrid_username, sendgrid_password)
server.send_message(message)
return None
except (smtplib.SMTPException, ssl.SSLError) as e:
return f"Failed to send email: {str(e)}"
if __name__ == "__main__":
sendgrid_username = "apikey" # This is typically "apikey" for SendGrid
sendgrid_password = "SG.xxxxx" # Replace with your actual SendGrid API key
sender_email = "[email protected]"
recipient_email = "[email protected]"
result = test_smtp_connection(
sendgrid_username, sendgrid_password, sender_email, recipient_email
)
if result is None:
print("Email sent successfully")
else:
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment