Skip to content

Instantly share code, notes, and snippets.

@apiarian apiarian/
Last active Aug 29, 2015

What would you like to do?
python3 email robot to be run periodically
#! /usr/bin/env python3
# is an email robot
# It connects to an IMAP mail server, looks at all of the messages,
# picks out the ones that have just a U or u in the Subject: header,
# scans them for all of the image attachments, saves them to a
# web-server accessible uploads folder, and replies to the message
# through the SMTP server with the URL(s) of the uploaded photos.
# The images are renamed to a UUID. Any message that got a reply is
# then deleted from the IMAP server.
# This script was designed to be run periodically on the server.
# Configurtion variables below
PORT = 143
USER = ''
PASSWORD = 'password of user'
DIRECTORY = '/server/static/upload/directory/'
SERVER_USER = 'newfileusername'
SERVER_GROUP = 'newfileusergroup'
MAIL_FROM = 'Super Mailbot <>'
import ssl, imaplib, email
import mimetypes
import uuid
from os import path
import os, pwd, grp
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
server = imaplib.IMAP4(SERVER,port=PORT)
context = ssl.create_default_context()
typ, data = server.starttls(ssl_context=context)
if typ == 'OK':
#print('TLS sesion started')
raise Exception('TLS session failed to start')
typ, data = server.login(USER,PASSWORD)
typ, data =
#print('%d messages in the INBOX'%(int(data[0])))
class Image:
typ, data =, 'ALL')
for num in data[0].split():
typ, data = server.fetch(num, '(RFC822)')
message = email.message_from_bytes(data[0][1])
images = []
if message['Subject'].lower() == 'u':
for part in message.walk():
if part.get_content_maintype() == 'image':
filename_extension = '.'+part.get_filename().split('.')[-1].lower()
possible_extensions = mimetypes.guess_all_extensions(part.get_content_type(), strict=True)
if filename_extension not in possible_extensions:
filename_extension = possible_extensions[0];
filename = str(uuid.uuid4()) + filename_extension
full_filename = path.join(DIRECTORY, filename)
full_url = URL_BASE + filename
img = Image()
img.original_filename = part.get_filename()
img.filename = filename
img.full_filename = full_filename
img.url = full_url
part_data = part.get_payload(decode=True)
with open(full_filename,'wb') as f:
uid = pwd.getpwnam(SERVER_USER).pw_uid
gid = grp.getgrnam(SERVER_GROUP).gr_gid
os.chmod(full_filename, 0o664)
if len(images):
reply = MIMEMultipart()
reply['From'] = MAIL_FROM
reply['Subject'] = 'RE: ' + message.get('Subject','')
if 'Reply-To' in message.keys():
reply['To'] = message['Reply-To']
reply['To'] = message['From']
if 'Message-Id' in message.keys():
reply['In-Reply-To'] = message['Message-Id']
if len(images) > 1:
content_string = 'Your images have been uploaded to the following urls:\n\n'
content_string = 'Your image has been uploaded to the following url:\n\n'
for image in images:
content_string += '\t"%s": %s\n'%(image.original_filename,image.url)
content = MIMEText(content_string)
smtp_server = smtplib.SMTP(SERVER)
smtp_server.login(USER, PASSWORD)
typ, data = server.close()
typ, data = server.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.