Mailgun integration in replit
Tue Jan 07 2025 15:38:25 GMT+0000 (Coordinated Universal Time)
Saved by
@miskat80
Example code
import smtplib
from email.mime.text import MIMEText
# SMTP configuration
smtp_host = 'smtp.mailgun.org'
smtp_port = 587
username = 'postmaster@YOUR_DOMAIN_NAME'
password = 'YOUR_API_KEY'
# Create the message
msg = MIMEText("This is a test email.")
msg['Subject'] = "Test Email"
msg['From'] = "noreply@yourdomain.com"
msg['To'] = "recipient@example.com"
# Connect and send the email
try:
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls() # Secure the connection
server.login(username, password)
server.send_message(msg)
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
Based on the code, here's the current working mail configuration:
In mail_config.py:
SMTP Server: smtp.mailgun.org
Port: 587
TLS: Enabled
Authentication: Using username/password
Required Environment Variables (set these in Replit Secrets):
MAILGUN_SMTP_USERNAME
MAILGUN_SMTP_PASSWORD
MAIL_DEFAULT_SENDER
The configuration initializes mail with:
app.config.update(
MAIL_SERVER='smtp.mailgun.org',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME=smtp_username,
MAIL_PASSWORD=smtp_password,
MAIL_DEFAULT_SENDER=sender
)
Sends emails using direct SMTP with starttls() for security
The key changes that made it work were:
Using port 587 instead of 465
Enabling TLS instead of SSL
Using direct SMTP connection with proper starttls() initialization
Proper error handling and logging
Keep these settings in your Replit Secrets for future implementations.
MAIL_DEFAULT_SENDER
••••••••
MAILGUN_DOMAIN
••••••••
MAILGUN_SMTP_PASSWORD
••••••••
MAILGUN_SMTP_USERNAME
••••••••
MAILGUN_API_KEY
••••••••
content_copyCOPY
Comments