Skip to content

Q&A · Answered

How to send emails in Python

asked 9 months, 2 weeks ago 775 views 1 answer
37

I need to send automated emails from my Python script. How do I do this?

1 Answer

One accepted
5

Accepted answer

Not confirmed since it was written, 9 months, 2 weeks ago
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Email configuration
smtp_server = "smtp.gmail.com"
port = 587
sender = "your@gmail.com"
password = "app_password"

# Create message
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = "recipient@example.com"
msg['Subject'] = "Test Email"

body = "This is a test email from Python."
msg.attach(MIMEText(body, 'plain'))

# Send email
with smtplib.SMTP(smtp_server, port) as server:
    server.starttls()
    server.login(sender, password)
    server.send_message(msg)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.