DEV Community

loading...
Cover image for Compose an email with markdown and send it with a Python script

Compose an email with markdown and send it with a Python script

aahnik profile image Aahnik Daw ・3 min read

Recap

In the previous article of this series, we had written a simple script to send an email with Python.

Let's recap the steps:

  • we first imported SMTP class from smptplib
  • we then defined the variables HOST,PORT,SENDER and PASSWORD
  • we then created an object of the SMTP class named server
  • Now call multiple server functions:
    1. connect
    2. ehlo
    3. starttls
    4. ehlo
    5. login
  • define the RECIPIENT and MESSAGE
  • send the email by calling server.sendmail

To see the code, read my previous article.

Let's Enhance

In this article, we will take further what we have learned in the previous article.

We will add some new features to our script:

  • rich-text via markdown.
  • setting a subject of the email.
  • using an alias name for the sender (you can set the sender's display name to be anything, like "Mr. Bean", irrespective of your actual email address).

alt text

Markdown

In the modern world, plain text looks boring. Professional emails have some logo, or title image, along with the richly formatted text.

Writing HTML is time-consuming, so we will use the markdown format, to compose beautiful emails.

If you are not familiar with the markdown formatting, then you should learn it because:

  • it is used to write posts in dev.to
  • it is commonly used to write the README file for your GitHub projects

To deal with markdown in python, we need the markdown package.

So install it via pip.

❯ pip install Markdown
Enter fullscreen mode Exit fullscreen mode

Write the code

Let's say we will write our email in a file called compose.md. Our script should send the content of that file as an email to our recipient.

Delete the old send.py that we have written last day. Let's refactor our code, to make it more mature and maintainable.

Let's define all our variables in a file called settings.py

# settings.py

HOST = 'smtp.gmail.com'
PORT = 587
SENDER = 'youremail@gmail.com'
PASSWORD = 'your12434(893**!@password'
RECIPIENT = 'some@example.com'
MESSAGE_FILE = 'compose.md'
DISPLAY_NAME = 'Mr. Bean'
Enter fullscreen mode Exit fullscreen mode

Now let's write down the send.py

# send.py

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from smtplib import SMTP

import markdown

from settings import (HOST, PORT,
                      SENDER, DISPLAY_NAME, PASSWORD,
                      RECIPIENT, MESSAGE_FILE)


with open(MESSAGE_FILE) as file:
    message = file.read()


server = SMTP(host=HOST, port=PORT)
server.connect(host=HOST, port=PORT)
server.ehlo()
server.starttls()
server.ehlo()
server.login(user=SENDER, password=PASSWORD)

multipart_msg = MIMEMultipart("alternative")

multipart_msg["Subject"] = message.splitlines()[0]
multipart_msg["From"] = DISPLAY_NAME + f' <{SENDER}>'
multipart_msg["To"] = RECIPIENT

text = message
html = markdown.markdown(text)

part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")

multipart_msg.attach(part1)
multipart_msg.attach(part2)


server.sendmail(SENDER, RECIPIENT, multipart_msg.as_string())

print('Sent email successfully!')


Enter fullscreen mode Exit fullscreen mode

That's it. Coding is over. Now let's run the script send.py.

❯ python send.py
Sent email successfully!
Enter fullscreen mode Exit fullscreen mode

Your output will look like this 👆 if you did everything alright. The email will be sitting right in the recipient's inbox.


I am Aahnik Daw and you can follow me on GitHub and dev.to to stay updated with my latest repos and articles.

Discussion (7)

pic
Editor guide
Collapse
jbalagnaranin profile image
Jérémie Balagna-Ranin

Hello and thank you for this simple yet realllly useful article :D

Just a tip to complete the subject: following the reading, I did a quick search and found there're easy way to replace your personal email by a simple server on Linux : plesk.com/blog/various/setting-up-...

@aahnik maybe for a fourth article ;)

Collapse
aahnik profile image
Aahnik Daw Author

thats a great idea.

actually i have a plan to make a series on self hosted software.

self hosted cloud, email, and more.

will come some day in future.

you may follow me to get notified.

Collapse
jbalagnaranin profile image
Jérémie Balagna-Ranin

Nice ! :D

I'll keep an eye on your future articles ;-)

Collapse
cookrdan profile image
Dan

Awesome. Was wondering how to do the display name or “alias” and couldn’t figure it out before. I will give this a try. Thanks for the simple code and explanations.

Would love to see how to do all the different types of attachments.

I haven’t looked at my incomplete script for a while. I had inline images from markdown working. That took a little bit of juice if I remember. But attaching other things like PDFs or whatever I haven’t attempted yet.

Collapse
aahnik profile image
Aahnik Daw Author

in the next (and last) article of this series, I will discuss about the attachment of files.

thank you for your kind feedback. ❤️

Collapse
aahnik profile image
Aahnik Daw Author

You may follow me, to get notified of the next article of the series.

Collapse
cjsmocjsmo profile image
Charlie J Smotherman

What would really be nice is to show how to recieve an email and respond to it with python (ie no services like Twillo)