Posted by virantha on Mon 04 November 2013

Creating new notes and attaching files using Evernote's Python API

Documents to Evernote

I managed to piece together how to attach a new PDF file to an Evernote note using their Python API, so I thought it might be useful to have a post that has all of this information together in one place.  I've put together a complete example that will:

  1. Authenticate to Evernote using a developer token (Oauth2 is a topic for another day)
  2. Check if a notebook exists; if not, it will create it for you.
  3. Create a new note in the notebook
  4. Attach a PDF file to that note (including calculating the necessary MD5 hash)
  5. Upload the new note

The complete file is shown at the end of this post, and I'll go through each function separately in the next sections.

1   Imports

Here's the complete set of imports that took me a while to track down, even from Evernote's own examples:

2   Authentication

And here's how to do the authentication using a developer token (Go to the following places to get a token: Sandbox evernote server or Production Evernote server

The important thing is to keep the EvernoteClient object around in self.client, as this will proved the authenticated access to the note stores.

3   Handle notebooks

The next step is to check whether the required notebook is available, or if we need to make it. See the _check_and_make_notebook function.

We use the get_note_store API call to get all the notebooks, and return a dict with the notebook name mapping to the notebook, in function _get_notebooks. Then, if the desired notebook is present, we update the stack (in Evernote, a notebook can be in a collection called a "stack" of notebooks) and return the notebook pointer. If not, we create a new notebook using the Types.Notebook() call, and store it using the createNotebook API call in the note_store.

4   Create the new note with attachment

Next is the real meat of this example, where we create the note with the attachment:

We create a new note using Types.Note(), and set its containing notebook using the GUID of the notebook. We then start setting the contents of the note using the Evernote markup language. All the text and attachment links must be inside the "en-note" tag. The content is then built up as follows:

  • Read in the PDF file to attach
  • Calculate the MD5 hash
  • Create a new Data container for Evernote and store the hash, size, and data from the file
  • Create a link to this file to insert into the content of the note
  • Create a Resource type to hold the PDF Data, and put it into a Resource list
  • Append the resource list to the note
  • Return this newly formed note

5   Uploading the note

The final step is to upload the note:

6   Complete example

© Virantha Ekanayake. Built using Pelican. Modified svbhack theme, based on theme by Carey Metcalfe