Hello,
in the “Requests & Suggestions” I asked for the possibility to import email directly from an IMAP-mailserver to DEVONthink.
This would improve my workflow for all kinds of personal notes, because I could send or save notes to my mail INBOX or Drafts.
Using the email-program or its web-interface is quite common to me. One could also use it when you’re on the go. Just use the smartphone, without need of special software.
Because there seems to be no solution at the moment, I started coding a tiny script to do this job. It’s made, to import emails from an IMAP-server and save them to the DEVONthink Inbox.
Not all emails should be imported, but the ones marked with "N: " at the beginning of the email-subject.
Here is my first shot. Maybe here is some one interested in helping to improve it.
Vinz
It does:
- Connect to my IMAP server and download all emails with “Note …” in subject.
- Store them as textfiles to the DEVONthink Inbox for further handling.
- Subject is the filename. Content is the content.
But be aware:
- It re-downloads emails, that already have been downloaded.
- It overwrites files with same name in Inbox.
- There is no error handling.
- There are names, passwords and absolute path in the script.
- This is for testing only.
To improve:
- Save text or html
- Save attachments, especially PDFs
# Python
import imaplib, email
import getpass # maybee use of: mail.login(getpass.getuser(), getpass.getpass())
import os, re, datetime
# = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# This program connects to your IMAP-server and downloads
# emails with subject beginning with "Note " to DEVONthink.
#
# Disclaimer: This is for amusement only. Never execute
# this on any system!
# 2011-11-13 Vinz
# 2011-11-18 Vinz minor improvement
# = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# function to get email plaintext
def get_first_text_block(email_message_instance):
maintype = email_message_instance.get_content_maintype()
if maintype == 'multipart':
for payload in email_message_instance.get_payload():
if payload.get_content_maintype() == 'text':
return payload.get_payload()
elif maintype == 'text':
return email_message_instance.get_payload()
# = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# function to get emails: Subject beginning with "N: " and maximum 30 days old
def get_my_notes(mail_instance):
date = (datetime.date.today() - datetime.timedelta(30)).strftime("%d-%b-%Y")
result, data_mails = mail_instance.uid('search', None, '(SENTSINCE {date} HEADER Subject "N:")'.format(date=date))
email_uids = data_mails[0].split()
ret_val = []
for email_uid in email_uids:
print email_uid
result, data_onemail = mail_instance.uid('fetch', email_uid, '(RFC822)')
raw_email = data_onemail[0][1]
email_message = email.message_from_string(raw_email)
email_subject = email_message['Subject']
email_text = get_first_text_block(email_message)
ret_val += [[email_subject, email_text]]
return ret_val
# = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# function to save my notes to DEVONthink
def save_notes(my_notes):
i = 0
for note in my_notes:
filename = note[0]
filename = re.sub("^N[: ]\s*(?i)", "", filename)
filename = re.sub(r"[\/\\\:\*\?\"\<\>\|.]", '_', filename)
content = note[1]
if re.match("\<html\>(?i)", content):
filename = filename + ".html"
else:
filename = filename + ".txt"
inbox_path = os.path.join(os.environ['HOME'], "Library/Application Support/DEVONthink Pro 2/Inbox/")
if not os.path.exists(inbox_path):
print "Can't find DEVONthink INBOX. Check path in script."
return
filepath = os.path.join(inbox_path, filename)
filepath = unique_filename(filepath)
f = open(filepath, 'w+')
f.write(content)
f.close()
print "Saved new note: " + filename
i+=1
print "{0} new messages saved.".format(i)
# = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# function to create a unique filename
# may have security issues: see
# http://stackoverflow.com/questions/183480/is-this-the-best-way-to-get-unique-version-of-filename-w-python
def unique_filename(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while os.path.lexists(file_name):
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
return file_name
# = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# main program
# connect to imap server inbox
mail = imaplib.IMAP4_SSL('imap.domain.com')
mail.login('your.name@domain.com', 'your_password')
mail.select("INBOX")
# mail.select("Drafts")
# get my notes an save to DEVONthink
notes = get_my_notes(mail)
save_notes(notes)
mail.close()
mail.logout()