Mike Levin SEO

Future-proof your technology-skills with Linux, Python, vim & git... and me!

← Using GNU Screen to Monitor Linux System Daemon Service
Knowing what GNU screen you're on with .screenrc →

Sending Emails With Python Through SMTP

by Mike Levin

Friday, July 29, 2022

These last few videos were quite wondrous. I doubt they’ll get any traction in YouTube because I have not made it fun or palatable enough to absorb the importance, but I’ll keep forging ahead and forge a very clear path for folks to follow, which I’ll clean up and make more appealing. But the raw work keeps getting pushed out.

Let’s get this thing emailing them! Let’s get some barebones stuff in place.

import smtplib

msg = '''Dear intrepid explorer,

We can write it across multiple lines, however because we're using
smtp protocol which is archaic and IBM-PC-biased, we need to include
carriage returns and linefeeds between lines. So after we compose
our message, we can do that with a Python list comprehension.

Do you comprehend?


Mike Levin'''

pcmsg = [f"\r\n{line}" for line in msg.split('\n')]

with open('mail_from.txt') as fh:
    email, paswd = [x.strip() for x in fh.readlines()]

with open('mail_to.txt') as fh:
    mail_to = [x.strip() for x in fh.readlines()]

server = smtplib.SMTP('smtp.gmail.com', 587)
server.login(email, paswd)

BODY = '\r\n'.join([f'To: {", ".join(mail_to)}',
                    'From: %s' % email,
                    'Subject: testing',
                    '\r\n', msg])

    server.sendmail(email, mail_to, BODY)
    print ('email sent')
    print ('error sending mail')