Table of Contents
Needing to send mail is a very common thing when building a dynamic backend or app. You'll want to inform your users of important events like a successful sign up, any major updates or changes, a change in the status of their accounts, a successful purchase, and much more.
You've got mail!
Sending Mail
Python offers the smtplib
module that allows us to use the Simple Mail Transfer Protocol (SMTP) to send mail between mail servers.
Let's take use smtplib
:
PYTHONimport smtplib
sender = "[email protected]"
receivers = ["[email protected]"]
message = """From: Hello <[email protected]>
To: To You <[email protected]>
Subject: Email sent using Python!
This is a test email sent using Python.
"""
try:
smtpObj = smtplib.SMTP("localhost")
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email."
except SMTPException:
print "An error occurred trying to send email."
A email requires the From
, To
, and Subject
headers. We included all of them in the message variable. From there we defined a new mail server from localhost
. Then we simply send the email.
If you are using a remote mail server, you can initialize your object like this:
PYTHONimport smtplib
server = "smtp.sabe.io"
port = 1337
smtplib.SMTP(server, port)
Sending HTML Mail
You can send HTML email just like you send plain text emails. The only difference is that you need to add a Content-type
header along with a MIME-Version
header.
Here's how that might look:
PYTHONimport smtplib
sender = "[email protected]"
receivers = ["[email protected]"]
message = """From: Hello <[email protected]>
To: To You <[email protected]>
MIME-Version: 1.0
Content-type: text/html
Subject: HTML email sent using Python!
This is a test HTML email sent using Python.
<h1>Sabe.io</h1>
<h2>Become a better developer</h2>
"""
try:
smtpObj = smtplib.SMTP("localhost")
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email."
except SMTPException:
print "An error occurred trying to send email."
Resources
- Getting Started with Solid
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js