Python comes with a couple of libraries that allows us to create e-mail messages and send them. These are the email
and smtp
libraries.
Creating the e-mail
Creating an e-mail using Python is made easy with the email
library. We'll just define the content, and its metadata (From, To, Subject).
from email.message import EmailMessage
email = EmailMessage()
email['Subject'] = 'Test email'
email['From'] = '[email protected]'
email['To'] = '[email protected]'
email.set_content('Hello, John')
Sending the e-mail
Sending the e-mail can be a bit more tricky. E-mail sending goes through SMTP, so we'll need an SMTP server that can process sending it.
If you are working in a corporate environment, you'll probably have access to an SMTP server. If you don't, you can always use Gmail or Hotmail to send e-mails. Warning: don't send large amounts of e-mail using personal accounts. If many people mark your e-mails as spam, you could see deliverability of your personal e-mails go down.
We'll send our e-mail using the smtp
library.
Log in to the Gmail SMTP server
In this example we'll be using a fake Gmail account to send messages. You can use your own account if you wish!
import smtplib
s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login('[email protected]', 'password')
Sending the e-mail
Once we've got the MIMEMultipart
message and we've logged in, we're ready to send it.
s.send_message(email)
s.quit()
Complete code
Below is the complete code you can use to send e-mails with Python. Try putting some or all of it into functions so that it becomes really simple to re-use it!
import smtplib
from email.message import EmailMessage
email = EmailMessage()
email['Subject'] = 'Test email'
email['From'] = '[email protected]'
email['To'] = '[email protected]'
email.set_content('Hello, John')
s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login('[email protected]', 'password')
s.send_message(email)
s.quit()
It's quite straightforward to send e-mails using Python! All we have to do is:
- Create the e-mail using the
EmailMessage
object; - Set up our SMTP server connection;
- Send the message!
Enjoy sending e-mails from your Python apps! If you are developing an app that will send many more e-mails, it could be worthwhile looking into an e-mail service such as Mailgun.