How to Send an Email with Python

How to send an email with Python?

I recommend that you use the standard packages email and smtplib together to send email. Please look at the following example (reproduced from the Python documentation). Notice that if you follow this approach, the "simple" task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
with open(textfile, 'rb') as fp:
# Create a text/plain message
msg = MIMEText(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

For sending email to multiple destinations, you can also follow the example in the Python documentation:

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
# Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type.
with open(file, 'rb') as fp:
img = MIMEImage(fp.read())
msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()

As you can see, the header To in the MIMEText object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the sendmail function must be a list of strings (each string is an email address).

So, if you have three email addresses: person1@example.com, person2@example.com, and person3@example.com, you can do as follows (obvious sections omitted):

to = ["person1@example.com", "person2@example.com", "person3@example.com"]
msg['To'] = ",".join(to)
s.sendmail(me, to, msg.as_string())

the ",".join(to) part makes a single string out of the list, separated by commas.

From your questions I gather that you have not gone through the Python tutorial - it is a MUST if you want to get anywhere in Python - the documentation is mostly excellent for the standard library.

How to send an email using python after Google's policy update on not allowing just username and password?

Here is a more precise answer with all the main steps. I hope it will help other people.

  1. Log in into your email account: https://myaccount.google.com

  2. Then go to the security part

Sample Image

Be sure that you have turn on two steps verification and click on "App password"

Sample Image


  1. After select email and the corresponding device

Sample Image


  1. It will generate a password that will look like this; it is this password that you have to use in your python script.

Sample Image


  1. This password will appear here; in this place, you will have the option to erase it (so it will be no longer be useful to connect to your email account).

Sample Image

Hope it will help other people!

Sending Email to outlook using gmail server in python

You need to use the proper MIME type to specify the type of content. Replace plain with text/plain for the body and image with image/png for the image. That way outlook (or any mail client for that matter) will know how to present the body and how to preview the attachment.

Send email via mail command in python script

The immediate problem is that strings in the shell need to be quoted if they contain newlines or etc. See When to wrap quotes around a shell variable.

But more fundamentally, you really don't want to use os.system here like this. Like its documentation already tells you, you generally want to prefer subprocess.

import subprocess

subprocess.run(
["mail", "-s", "Test email", "name@server.com"],
input=text, text=True, check=True)

or use smtplib to send email natively (or, conversely, don't use Python at all if all you need is a simple shell script, though you'd still need to fix the quoting then).

mail is poorly portable so if you haven't tested this on your system already, it might have additional problems.
Perhaps see also How do I send a file as an email attachment using Linux command line?

How do I now (since June 2022) send an email via Gmail using a Python script?

Google has recently made changes to access of less secure apps (read here: https://myaccount.google.com/lesssecureapps).

In order to make your script work again, you'll need to make a new app password for it. Directions to do so are below:

  • Go to My Account in Gmail and click on Security.
    After that, scroll down to choose the Signing into Google option.
  • Now, click on App Password. (Note: You can see this option when two-step authentication is enabled). To enable two-step authentication:
    1. From the Signing into Google, click on the Two-step Verification option and then enter the password.
    2. Then Turn ON the two-step verification by entering the OTP code received on the mobile.

(Here's a quick link to the same page: https://myaccount.google.com/apppasswords)

  • Here, you can see a list of applications, choose the required one.
  • Next, pick the Select Device option and click on the device which is being used to operate Gmail.
  • Now, click on Generate.
  • After that, enter the Password shown in the Yellow bar.
  • Lastly, click on Done.

(Source: https://www.emailsupport.us/blog/gmail-smtp-not-working/)

Simply switch out the password the script is using for this newly generated app password. This worked for me and I wish the same for you.

I hope this helps!

What's solution for sending emails from python while gmail the less secure apps is not enabled anymore

If you want to continue using Gmail SMTP, you can set it up by setting an app password. An app password works like an alternate password for your account. It can only be used by the applications you share it with, so it’s more secure than sharing your primary password.

Here's how you can set it up: https://support.google.com/accounts/answer/185833?hl=en



Related Topics



Leave a reply



Submit