fetchmail is a full-featured IMAP and POP client

Install


sudo apt-get install fetchmail

Configure How Mail Is Handled

Now create a file named ~/.fetchmailrc in your home directory.


sudo nano

Enter this:


poll imap.gmail.com
protocol IMAP
user "AGmailUser@gmail.com" with password "TheGmailPassword" mda "/home/pi/myfetchmailparser.sh"
folder 'INBOX'
fetchlimit 1
#keep
ssl

Fetchmail by default will try and pass mail to port 25 on localhost.  Using mda (mail delivery agent) tells it to pass it to the mda instead, which in this case is a script we will create.

If you don't want the email to be deleted from the mailbox remove the # commenting out the keep line (this doesn't mean the email will be read again though when you next run the script, it will simply remains in the inbox marked as read.  However if you go to the mailbox via say gmails web interface and mark the email as unread again then it will be included the next time you call the script – useful for testing)

Press CTRL+X to exit the file, select save and enter:


/home/pi/.fetchmailrc

Now we need to create the script which we'll set up to simply write received emails out to a text file each.


sudo nano

Enter this:


FilenameUniqueId=$(date +"%Y%m%d_%H%M%S_%N")
OutputFile="/var/tmp/mail"$FilenameUniqueId
echo "" > $OutputFile
while read x
do 
#echo $x
echo $x >> $OutputFile
done

Press CTRL+X to exit the file, select save and enter:


/home/pi/myfetchmailparser.sh
Set Permissions

Fetchmail is very particular about permissions.

Set the current user as the owner (only the current user can run .fetchmailrc):


sudo chown pi .fetchmailrc
sudo chown pi myfetchmailparser.sh

Set the files permissions


sudo chmod 710 .fetchmail.rc
sudo chmod 710 myfetchmailparser.sh

(these may not be optimum settings – we just wanted to get it working and this worked!)

Running It

fetchmail > /dev/null

Now look in the /var/tmp/ folder and you should see the new file which will contain the email text.

If you need to do this from inside a C application which is running as root (e.g. an application using the IO pins) you can call it like this to make the call as the "pi" user instead of root (which won't work)


	system("su - pi -c \"fetchmail > /dev/null\"");

 

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.