Sending email programmatically in python

Mandar Bhide
3 min readJul 25, 2020

Email has now become an important part of our lives. Right from university admissions to job applications and from file/text transfer to service authentications require email. Recently, while developing a website, I came across need to send an email to the user. I felt like sharing my solution to my fellow developers. Let’s get started.

This article will discuss following points:

  • Using flask as a client.
  • Using environment variables
  • Sending email from the code

We need two packages for this. First is flask, which is core of this approach, and other is flask-mail. With pip, these can be easily installed with ‘pip install flask’ and ‘pip install flask-mail’.

Getting back to editor, first we need to import the required packages as:

from flask import Flaskfrom flask_mail import Mail, Messageimport os

Then we create and configure our flask app as:

app = Flask(__name__)app.app_context().push()app.config['MAIL_SERVER'] = 'smtp.googlemail.com'app.config['MAIL_USE_TLS'] = Trueapp.config['MAIL_PORT'] = 587

Here, we set MAIL_SERVER to smtp.googlemail.com, which is free smtp mailing service offered by google. Then there is MAIL_USE_TLS or MAIL_USE_SSL parameter. These are related to network security. Those having deeper knowledge can use any of these. Here we’ll use MAIL_USE_TLS. Take care, that this parameter directly affects the next one, which is MAIL_PORT. Set MAIL_PORT to 587 for TLS and 465 for SSL. Remember, you CANNOT use any other combination.

Now, before moving to next parameters, we need to set some environment variables for our email address and password of the gmail account from which we’ll send mail. (Quick tip: You need to create a gmail account, if you don’t have one.) To set environment variables, refer following links:

We need to set two environment variables here, first for our email id and other for our password, so that our credentials remain hidden from anyone seeing the code. Suppose our variable names are EMAIL and PASS, then we set the parameters as:

app.config['MAIL_USERNAME'] = os.environ.get('EMAIL')app.config['MAIL_PASSWORD'] = os.environ.get('PASS')

Now its time to initialize our Mail object and create a message. Message constructor takes subject as mandatory argument and other optional arguments such as, recipients,body,sender,cc,bcc etc. (Warning: Take care while setting sender parameter, to avoid the mail getting classified as spam.) For more info on these parameters you can refer flask-mail documentation.

After creating the message, we can simply send it by mail.send(msg)

Will this code send any mail? NO! Remember, we haven’t yet run our app. Here, we use a typical if __name__ == “__main__” block. For those having C or Java background, this block functions roughly similar to main(). In this block, we run our app with app.run():

if __name__ == "__main__":    app.run()

Save and run this app. Still there are very high chances that you run into issue saying smtplib.SMTPAuthenticationError. This is because google classifies such apps as ‘possibly harmful apps’ and blocks any sign-in. To overcome this issue, you need to turn on ‘Allow less secure apps’ in your google account’s settings. Also disable 2FA (2 Factor Authentication). After making changes to account settings, the code should run smoothly.

Thanks a lot for following it up to here. Hope you enjoyed this article and found it useful. Let me know about any issue in the comment section. Complete code can be found here. Happy coding!

--

--

Mandar Bhide

Computer Engineering student | Web and app developer| Love to learn technologies :)