Home » programming » Send email using Python 3

Send email using Python 3

A while ago, I had posted a bash script which could spam a friend with a message. It required a computer which was capable of running the mail command, something not true for simple users.

Now, I wanted to send to a friend of mine a message per hour to remind her how old she is (it is her birthday today). I used my gmail account and a few pieces of code.

Because it took me some time to figure out how to make unicode work in the body of the message, I paste here my code for future reference. I found especially useful a blog post: Sending emails via Gmail with Python, which is unfortunately for Python 2. As you can see, the name of the packages and a few details for the unicode have changed.

A tiny detail: I keep a database of quotes using fortune, the unix program. I thought it would be nice to generate a quote and send it via email with each message.

#!/usr/bin/python

import smtplib
import time
from email.mime.text import MIMEText

import os

# authentication
gmail_user = 'email@example.com'
gmail_pwd = 'my_super_secret_password'

recipient = "buddy@example.com"
preable = """A
multiline
message.
"""
end_message = "\n\nRegards,\nΔημήτρης"


def mail(to, subject, text):
    msg = MIMEText(text.encode('utf-8'), 'plain', 'UTF-8')

    msg['From'] = gmail_user
    msg['To'] = to
    msg['Subject'] = subject.encode('utf-8')
    msg.set_charset('utf-8')

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)
    mailServer.sendmail(gmail_user, to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()


def get_quote():
    """ Generate a random message from a fortune collection. """
    f = os.popen("fortune /home/myle/myle-quotes")
    b = f.read()

    return b


def send_specific_message(counter, quote):
    """ Send a message with a specific structure. """
    topic = "A message (" + str(counter) + ')'
    message = preable + quote + end_message
    mail(recipient,
        topic,
        message)


def main():
    i = 0
    while True:
        i += 1
        quote = get_quote()
        send_specific_message(i, quote)
        time.sleep(60 * 60)


if __name__ == '__main__':
    main()
Advertisements

1 Comment

  1. Thanks for this! I’ve packaged it together as a class and it works great. Delighted with the ease of use!
    All the best,
    Cathal

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: