Twitter autofollow and DM using python-twitter, imaplib and gmail

The script will:

  1. connect via imap to gmail
  2. select the imap directory TwitterFollow (you should filter twitter follow notifications and label them with TwitterFollow)
  3. fetch the headers of all unread mails
  4. retrieve the twitter user screen_name that is following you from the headers
  5. attempt to create a friendship aka autofollow. If an error occurs is probably due to the fact you previously followed the user
  6. Send a direct message to thank for the following
  7. Flag the message as read so it won’t be fetched next time script runs

You could also check Twitter autofollow and direct message using python mechanize libgmail which is basically achieving the same goal but operate differently using reverse engineering on gmail web site.

Twitter autofollow and direct message using python mechanize libgmail


  • a valid gmail account
  • label your twitter follow notifications (E.g. I use TwitterFollow)
  • mechanize : a stateful programmatic web browsing
  • libgmail : a GA reverse engineered library
  • python-twitter : a wrapper around the Twitter API

IMPORTANT: because Gmail does not provide an API and does not intend to do that because of the ads, hacking libgmail to fetch the threads is a VIOLATION of Gmail TOS. This script should be use for documentation only. For production please consider using POP3 or IMAP to fetch the threads. To avoid your account being suspended or locked run the script no more than twice a day.