-
Notifications
You must be signed in to change notification settings - Fork 1
Emails
In this project, we're going to be writing automated emails fairly frequently - for example, when a user requests to have their username or password changed. Below is a guide to Mailtrap, the testing platform we're using to simulate automated emails, and how to write both code to send emails and testing code to simulate receiving emails.
Mailtrap is a service that allows us to simulate the sending and receiving of emails without actually doing so. This is very useful, since it allows us to make changes to our automated emails (add more info, change styling) without these emails being released to the general public. Furthermore, because Google disabled less secure apps, we can no longer use regular Gmail accounts to send/receive emails programmatically, and thus we have to rely on a third-party platform.
I have created a Mailtrap account under [email protected]
, and you can log in to the account to see if your tests work properly. Be sure to empty the inbox frequently, as there is a limit of 50 emails in the free plan.
You can use the functionality provided by flask-mail
to send emails via Mailtrap (or any other email address that you have access to, once we switch over).
All you have to do is construct a Message
according to flask-mail
's specs for messages, and import the mail
variable from common.plugins
. An example to send an email with Mailtrap:
from flask_mail import Message
from common.plugins import mail
def register():
# OTHER CODE HERE #
# Send it over to email
message = Message(
"Account registered for Week in Wonderland",
sender="[email protected]",
recipients=[json["email"]]
)
# TODO: convert to HTML message
message.body = f"Your code is: {code}"
mail.send(message)
When testing out our backend, we will need to see if emails are actually being sent, and if the content inside those emails are what we expect. Mailtrap uses POP3, so to read emails, we will have to use poplib
(which is a pre-installed package in Python).