As an Amazon Associate we earn from qualifying purchases.
Python can send email with no extra libraries. The built-in smtplib module connects to a mail server and hands it your message. This is handy for alerts from a script, a sensor reading sent from a Raspberry Pi, or a simple notification when a long job finishes.
This guide shows a short working example with Gmail, explains each step, and covers the most common error: “Blocked sign-in attempt for security reasons”. If you are new to the language, start with getting started with Python first.
How sending email in Python works
Email is sent using SMTP (Simple Mail Transfer Protocol). Your script does the following:
- Connects to the SMTP server of your email provider.
- Switches the connection to an encrypted one.
- Logs in with your account details.
- Sends the message from one address to another.
- Closes the connection.
For Gmail, the server is smtp.gmail.com. Port 587 is used with STARTTLS, and port 465 is used with SSL from the start of the connection.
Basic example: send a mail with the message “Hello”
The script below wraps everything in a function called send_email(). Replace the addresses and the password with your own.
def send_email():
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
#Next, log in to the server
server.login('jimmypulikottil@gmail.com', 'password')
#Send the mail
msg = "\nHello!" # The \n separates the message from the headers
server.sendmail("jimmypulikottil@gmail.com", "e4emerging@gmail.com", msg)
server.quit()
send_email()
Two small fixes were made to the original version of this code. The newline in the message must be written as \n (a backslash, not a forward slash), and the connection is now closed with server.quit() once the mail is sent.
What each line does
- smtplib.SMTP(‘smtp.gmail.com’, 587) opens a connection to Gmail’s server.
- ehlo() introduces your script to the server. It is called again after encryption starts.
- starttls() upgrades the connection to an encrypted one, so your password is not sent in plain text.
- login() signs in with your email address and password.
- sendmail() takes the sender, the recipient and the message text.
- quit() ends the session.
Fixing “Blocked sign-in attempt for security reasons”
The first time you run the script, Gmail may refuse the login and send you a security alert saying “Blocked sign-in attempt for security reasons”. Google does this because the sign-in came from a script rather than a normal browser or mail app.
In the original setup, the fix was to open the alert in your Gmail account, choose the option to allow access, and then run the script again. The message was then delivered.
Google has changed its account security over time, and it no longer supports sign-in with just your normal password for many accounts. If you still get a login error (often shown as SMTPAuthenticationError), try these steps:
- Turn on 2-Step Verification for the Gmail account.
- Create an app password in your Google account security settings.
- Use that app password in
server.login()in place of your normal password. - Run the script again.
An app password is a separate password that only works for one app or script. If it leaks, you can delete it without changing your main password.
A cleaner version using EmailMessage
Building the message as a plain string works, but it does not give you a proper subject line. The email.message.EmailMessage class handles headers for you and is easier to extend later.
import smtplib
from email.message import EmailMessage
def send_email(sender, app_password, recipient):
msg = EmailMessage()
msg['Subject'] = 'Hello from Python'
msg['From'] = sender
msg['To'] = recipient
msg.set_content('Hello!')
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(sender, app_password)
server.send_message(msg)
send_email('you@gmail.com', 'your-app-password', 'friend@example.com')
The with statement closes the connection automatically, even if something goes wrong. If you want to attach a file, read our guide on sending email with attachment in Python.
Keep your password out of the code
Writing your password directly in the script is fine for a quick test, but it is risky if you share the file or upload it to a public repository. Safer options include:
- Storing the password in an environment variable and reading it with
os.environ. - Using a separate config file that is not shared.
- Asking for the password when the script starts, which is covered in reading input in Python.
Also use a dedicated email account for scripts and alerts when you can, rather than your main inbox.
Common problems and how to solve them
- Authentication error: check the address and password, and use an app password if 2-Step Verification is on.
- Connection timed out: your network or firewall may block the SMTP port. Try port 465 with
smtplib.SMTP_SSL, or a different network. - Message lands in spam: add a clear subject and avoid sending many messages quickly.
- Odd text in the message: make sure line breaks use
\n, or useEmailMessage, which handles this for you. If you build text from several parts, see joining strings in Python.
Where to use this next
Once the basics work, you can send a mail when a sensor passes a limit, when a backup finishes, or when a script fails. For project ideas that could use email alerts, see these Raspberry Pi Python projects.
FAQ
Do I need to install anything to send email in Python?
No. smtplib and email are part of Python’s standard library, so you only need Python and an email account that allows SMTP access.
Why does Gmail say “Blocked sign-in attempt”?
Gmail treats a script login as a sign-in from an unfamiliar app. Approve the sign-in from the security alert, or better, turn on 2-Step Verification and use an app password.
Which port should I use for Gmail?
Use 587 with starttls() for the standard setup. Port 465 with SMTP_SSL also works if 587 is blocked on your network.
Can I send email to more than one person?
Yes. With EmailMessage, set the To header to several addresses separated by commas, and send_message() will deliver to all of them.