Receive and send emails in python

Viewed 52530

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?

9 Answers

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.

I do not think it would be a good idea to write a real mail server in Python. This is certainly possible (see mcrute's and Manuel Ceron's posts to have details) but it is a lot of work when you think of everything that a real mail server must handle (queuing, retransmission, dealing with spam, etc).

You should explain in more detail what you need. If you just want to react to incoming email, I would suggest to configure the mail server to call a program when it receives the email. This program could do what it wants (updating a database, creating a file, talking to another Python program).

To call an arbitrary program from the mail server, you have several choices:

  1. For sendmail and Postfix, a ~/.forward containing "|/path/to/program"
  2. If you use procmail, a recipe action of |path/to/program
  3. And certainly many others

Python has an SMTPD module that will be helpful to you for writing a server. You'll probably also want the SMTP module to do the re-send. Both modules are in the standard library at least since version 2.3.

poplib and smtplib will be your friends when developing your app.

The sending part has been covered, for the receiving you can use pop or imap

Depending on the amount of mail you are sending you might want to look into using a real mail server like postifx or sendmail (*nix systems) Both of those programs have the ability to send a received mail to a program based on the email address.

You can use emailpy

Install via pip3 install emailpy

import emailpy
manager = emailpy.EmailManager('your email', 'your password')
msg = manager.send(['who you are sending to', 'the other email you are sending to', subject='hello', body='this email is sent from Python', html='<h1>Hello World!</h1>', attachments=['yourfile.txt', 'yourotherfile.py'])
while not msg.sent:
    pass
print('sent')
messages = manager.read()
for message in messages:
    print(message.sender, message.date, message.subject, message.body, message.html, message.attachments)
    for attachment in message.attachments:
        print(attachment.name)
        attachment.download()
Related