today’s assignment is to send a text email to an arbitrary recipient by using an existing gmail account. We will send the email by using the blog’s favorite scripting language, Python. For you who wonder if we could attach an image or an arbitrary file to an email & send it with the main content, yes, we can, but in this article i would like to focus simply on text emails, without attachments.
- An existing gmail account
- Python’s S(imple)M(ail)T(ransfer)P(rotocol)lib module. smtplib is already installed with Python, thus you don’t need to “pip search” & “pip install” it.
With the following script, we can send an email to any number of recipients (“email@example.com”) through our existing gmail account (“firstname.lastname@example.org”). We need to build our email by filling the email content string (the variable message), then logon to the gmail server through the server’s smtp daemon, send the message & finally close connection with the smtp daemon of the gmail server. We use the smtp protocol because in the gmail case, gmail’s servers (to which we need to login in order to send the email) have attached & running an smpt daemon-service, allowing them to “listen” to smtp email requests.
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body # Prepare actual message
message = “”“\From:%sTo:%s\nContent-type:text/html\n
server = smtplib.SMTP_SSL(“smtp.gmail.com”)
server.sendmail(FROM, TO, message)
#print ‘successfully sent the mail’
except Exception as e:
#print “failed to send mail”
return Falseif __name__ == ‘__main__’:
Gmail Login Failure
In case the login() call fails with the following error
Please log in via your web browser and then try again
The page says: “Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can turn off access for these apps, which we recommend, or turn on access if you want to use them despite the risks”
and click on “Turn On” (if you want Google to allow you to send the email through your app/script).
At the moment, i have no clue how to send an email without turning that account feature to “Off“. Consider this as an assignment for yourself 🙂
Why wanting to send emails?
Because you would like to get notified by one of your programs in case of
- an abnormal behavior,
- a task completion,
- a data change,
in general, in case specific conditions have been met inside your code & something interesting just happened, while you are away from the console that executes your precious script. By using smtplib through the previous function, you could just fill the subject & content depending the occasion inside your code.
Now, go & spam yourselves.