Python Email Sender Script Example

This example shows how to send an email in Python using the standard library.

You will learn:

  • How to create a simple email message
  • How to connect to an SMTP server
  • How to log in and send the email
  • Which values you must replace before the script works

This page focuses on a small working script. It also covers common setup problems that beginners often hit.

Quick example

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'Test email from Python'
msg['From'] = 'your_email@example.com'
msg['To'] = 'friend@example.com'
msg.set_content('Hello from Python!')

with smtplib.SMTP_SSL('smtp.example.com', 465) as smtp:
    smtp.login('your_email@example.com', 'your_password')
    smtp.send_message(msg)

print('Email sent')

Replace the SMTP server, port, email address, and password with real values from your email provider. Some providers require an app password instead of your normal password.

What this example shows

This script demonstrates the basic steps for sending an email:

  • Build an email message with a subject, sender, recipient, and body
  • Connect to an SMTP server
  • Log in with your email account
  • Send the message

It uses:

  • smtplib to talk to the email server
  • EmailMessage to build the email

You do not need to install extra packages for this basic example. Both modules are included with Python.

Before you run the script

Before this can work, you need a few real values from your email provider:

  • An email account that allows SMTP sending
  • The correct SMTP server name
  • The correct SMTP port
  • A working password or app password

A few important notes:

  • Some providers do not let scripts use your normal password
  • Some providers require an app password
  • Some providers block sign-in attempts until you enable a security setting

An app password is a special password made for scripts or apps. It is often safer than using your normal account password directly.

How the script works

Here is the same script again:

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'Test email from Python'
msg['From'] = 'your_email@example.com'
msg['To'] = 'friend@example.com'
msg.set_content('Hello from Python!')

with smtplib.SMTP_SSL('smtp.example.com', 465) as smtp:
    smtp.login('your_email@example.com', 'your_password')
    smtp.send_message(msg)

print('Email sent')

Step by step:

  • import smtplib imports the module used to connect to the mail server
  • from email.message import EmailMessage imports the class used to create the email
  • msg = EmailMessage() creates a new email message object
  • msg['Subject'], msg['From'], and msg['To'] set the email headers
  • msg.set_content(...) sets the plain text body
  • smtplib.SMTP_SSL(...) opens a secure connection to the SMTP server
  • smtp.login(...) signs in to your account
  • smtp.send_message(msg) sends the email

If you are new to Python input, see Python input() function explained for a simple way to ask the user for values.

Important lines to explain

msg['Subject']

This sets the subject line that the recipient sees.

msg['Subject'] = 'Test email from Python'

msg['From']

This sets the sender address.

msg['From'] = 'your_email@example.com'

In many cases, this should match the account you log in with. If they do not match, some providers may reject the message.

msg['To']

This is the recipient email address.

msg['To'] = 'friend@example.com'

smtp.login(...)

This authenticates with the email server.

smtp.login('your_email@example.com', 'your_password')

If this line fails, the problem is often:

  • Wrong email address
  • Wrong password
  • App password required
  • Provider security settings blocking the login

smtp.send_message(msg)

This actually sends the email.

smtp.send_message(msg)

If the connection and login are correct, this sends the message to the server.

Expected result

If everything works:

  • The script prints Email sent
  • The recipient should receive a plain text email
  • The message may still be delayed, filtered, or sent to spam

Example output:

Email sent

Even when the script finishes without an error, delivery is not always guaranteed. The provider might still reject or filter the message later.

Safer way to handle passwords

Do not hard-code real passwords in a file you plan to share.

A simple beginner-friendly option is to ask for the password while the script runs:

import smtplib
from email.message import EmailMessage

sender = input("Enter your email address: ")
password = input("Enter your email password or app password: ")
recipient = input("Enter recipient email address: ")

msg = EmailMessage()
msg["Subject"] = "Test email from Python"
msg["From"] = sender
msg["To"] = recipient
msg.set_content("Hello from Python!")

with smtplib.SMTP_SSL("smtp.example.com", 465) as smtp:
    smtp.login(sender, password)
    smtp.send_message(msg)

print("Email sent")

This is better than saving the password in the script, but it still shows the password on screen while typing.

A more advanced next step is to use environment variables. If you are still learning, start with input() and move to safer storage later.

Common problems with email scripts

These are the most common reasons the script does not work:

  • Wrong SMTP host
  • Wrong SMTP port
  • Incorrect username or password
  • Using a normal password when an app password is required
  • Provider blocks sign-in from scripts
  • No internet connection
  • Firewall or network blocks the SMTP port

Other common causes include:

  • Using the wrong SMTP server address
  • Using the wrong SMTP port
  • Entering the wrong email password
  • Trying to send from an account that blocks SMTP access
  • Forgetting to match the From address with the login account

If you get an error, read the full message carefully. A good next step is learning Python errors and exceptions explained and how to handle exceptions in Python.

Simple debugging checks

Try these checks before changing a lot of code:

  • Make sure the email address in login() is correct
  • Check the SMTP server and port in your provider's documentation
  • Print the host and port before connecting
  • Try sending to your own email address first
  • Read the full error message instead of guessing

Useful test commands:

python email_sender.py
python -c "import smtplib; print('smtplib imported successfully')"
python -c "from email.message import EmailMessage; print('EmailMessage imported successfully')"

If imports fail, the problem may be with your Python installation or environment. If you see missing module errors in other scripts, read ModuleNotFoundError: no module named X fix.

Good next steps for readers

Once this basic version works, you can improve it by:

  • Adding HTML email content
  • Sending to multiple recipients
  • Attaching a file
  • Moving login details out of the script
  • Wrapping the send code in try and except

Here is a simple version with basic error handling:

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg["Subject"] = "Test email from Python"
msg["From"] = "your_email@example.com"
msg["To"] = "friend@example.com"
msg.set_content("Hello from Python!")

try:
    with smtplib.SMTP_SSL("smtp.example.com", 465) as smtp:
        smtp.login("your_email@example.com", "your_password")
        smtp.send_message(msg)
    print("Email sent")
except Exception as error:
    print("Could not send email:")
    print(error)

This does not fix every problem automatically, but it helps you see the real error instead of the program stopping with no explanation.

FAQ

Do I need to install a package to send email in Python?

No. For a basic SMTP example, smtplib and email.message are part of Python's standard library.

Why does my email script say login failed?

Usually the username, password, app password, or provider security settings are wrong.

Can I send HTML emails with Python?

Yes. You can use EmailMessage and add HTML content. For a first script, plain text is easier to test.

Why is my script correct but the email still does not arrive?

The provider may reject, delay, or filter the message. Check the spam folder and your provider settings.

See also