Question

Receive and send emails in python

How can I receive and send email in python? A 'mail server' of sorts.

I am looking into making an app that listens to see if it receives an email addressed to foo@bar.domain.com, and sends an email to the sender.

Now, am I able to do this all in python, would it be best to use 3rd party libraries?

 45  60109  45
1 Jan 1970

Solution

 23

Here is a very simple example:

import smtplib

server = 'mail.server.com'
user = ''
password = ''

recipients = ['user@mail.com', 'other@mail.com']
sender = 'you@mail.com'
message = 'Hello World'

session = smtplib.SMTP(server)
# if your SMTP server doesn't need authentications,
# you don't need the following line:
session.login(user, password)
session.sendmail(sender, recipients, message)

For more options, error handling, etc, look at the smtplib module documentation.

2008-12-08

Solution

 19

Found a helpful example for reading emails by connecting using IMAP:

Python — imaplib IMAP example with Gmail

import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com', 'mypassword')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, "ALL")

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

# fetch the email body (RFC822) for the given ID
result, data = mail.fetch(latest_email_id, "(RFC822)") 

raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads
2014-11-06