Skip to content
Advertisement

How to write a program to automatically download a file from email

I have an email account (like gmail or something) that gets a daily email with a file attached to it that has some data in it. Is there a way to have a program check the email everyday, say at midnight or something, download that file, and store the contents into a SQL database?

I’m familiar with Java, JavaScript, PHP, HTML, and Python. Is there a way to do this using what I already know, or would it require some other technology?

Advertisement

Answer

I like to use Python for this kind of tasks, it’s fast and minimalistic.

You can access mails using POP3 or IMAP protocol. Python contains modules to work with them: poplib and imaplib. POP3 is simpler, I advice to use it if you need just download mails and delete them after that.

IMAP is more advanced. Each message has it’s own UID, that identifies messages. New messages have greater UID then old one, so every time you run downloading, you just need to store somewhere (in file, database) the greatest UID of messages you processed and use it to find newer messages when you will run downloading next time. See here example of working with IMAP from Python.

To schedule downloading each X hours, you can choose from these options:

  1. Write application that download new messages, then sleep using sleep() function in infinite loop.
  2. Write application that just download new messages and finish its work. Schedule its runs externally using Cron tool.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement