Showing posts with label IMAP. Show all posts
Showing posts with label IMAP. Show all posts

Thursday, December 22, 2011

Managing your IMAP account using Perl


This perl script will give you a basic idea of how your IMAP account can be managed  via perl.  I have been using perl to manager certain tasks with my GMail account ( GMail provides both POP and IMAP services).

We make use of the Mail::IMAPClient perl module for manipulating imap accounts.  This script also prompts for a password from command line so that you don't have to hard code your password in the script.


### Module loading

### Mail::IMAPClient for manipulating IMAP accounts
use Mail::IMAPClient;

### Term::ReadKey is for accepting passwords from terminal
use Term::ReadKey;

### Ask for password
print "Enter Password:";
               ReadMode('noecho');
               chomp ( my $imapPassword = ReadLine(0)) ;
               ReadMode('restore');
print "\n";

### Provide your imap username here
my $imapUser = 'your.imap.user' ;

### Provide your imap server name
my $imapServer = 'your.imap.server.name';

### Provide your imap server port number, default is 993.
my $imapPort = 993;

my $imap = Mail::IMAPClient->new(
    Server   => $imapServer,
    User     => $imapUser,
    Port     => $imapPort,
    Password => $imapPassword,
    Ssl      => 1,
  )

or die "Can't connect to $imapServer as $imapUser: $@";

### You are now logged into the imap account.  Play around a bit

### Print all folders
my $folders = $imap->folders or die "List folders error: ", $imap->LastError, "\n";
foreach ( @$folders )  { print $. , " ) " , $_ ,"\n"; }

### Count messages in the Sent folder
my $msgcount = $imap->message_count('Sent');
print "Count $msgcount\n";

### Process all emails in the folder "Work"

## Start by selecting the Work folder
$imap->select('Work') or
    die("Couldn't select Work folder", $!);

## Load all message ids in Work folder to @msgs
my @msgs = $imap->messages or die "Couldn't get messages: $@\n";

## Backup message to $file

my $TS = time;
my $FILE = "imap_bakup_".$TS;
open MAILBACKUP, ">>", $FILE or die "Couldn't open $FILE"
print MAILBACKUP "Starting backup at time : $TS\n";}

foreach my $msgid (@msgs)
{
 $imap->message_to_file(MAILBACKUP,$msgid) or die "Couldn't backup $msgid: $@\n";
}

print MAILBACKUP "Finished backup";
close BACKUP;

## Delete all messages in "Work" folder
$imap->delete_message(\@msgs) or die "Couldn't delete message in folder Work: $@\n";

### Create new folder "Life"
$imap->create("Life") or die "Couldn't create folder Life: $@\n";

### Delete the folder "Life"
$imap->delete("Life") or die "Couldn't delete folder Life: $@\n";

### Expunge messages marked as deleted in the selected folder
$imap->expunge() or die "Couldn't expunge: $@\n";

### Close the selected folder
$imap->close or die "Couldn't close: $@\n";

### Logout IMAP
$imap->logout

Thursday, June 16, 2011

Configure mutt as IMAP client

     Mutt is a lightweight yet powerful command line email client.  We will look at a minimal configuration for an IMAP account here.

     Mutt has a global configuration file in either /etc/Muttrc or /usr/local/share/mutt/Muttrc.   This is useful for configuring system wide settings.  But to configure your own account you have to configure your personalized muttrc file in your home directory at ~/.muttrc.

     Here is a sample muttrc file that can get yo start  off with mutt.  Explanations are given as comments.


## Set your imap server name and port here.
set folder=imaps://my.imap.server.name:imapPort/
## Where to look for the mails
## the "+" simbol means, append this to the value of "folder" setting
set spoolfile=+Inbox
## Your imap username
set imap_user=my_imap_user
## Set your imap password - Not preferred for security reasons
## If not provided mutt will prompt you for a password
set imap_pass=my_imap_pass
## Setting sent folder ( note the "+" sign )
set record=+Sent
## Setting draft folder ( note the "+" sign )
set postponed=+Drafts
## To cache downloaded header
## Good for performance
## directory should be manually created
set header_cache=~/.mutt/cache/headers
set message_cachedir=~/.mutt/cache/bodies
## Your preferred editor for composing
set editor=vim
## How to sort your mail
set sort='last-date-received'

Saturday, February 12, 2011

Test your IMAP server with Telnet

     Internet Message Access Protocol version 4 (IMAP 4 ) is an email retrieval protocol which is a lot more robust than the Post Office Protocol version 3 ( POP3).   It provides features like name spaces,folders,sub folders,flags etc.. A discussion of all the features is beyond the scope of this article.  Here we will see how we can test the basic functionalities of an IMAP server using telnet.

     First, establish a connection to the IMAP server using telnet on port 143.

safeer@penguinpower:~$ telnet imap.safeer.in 143
Trying 10.25.0.3...
Connected to imap.safeer.in
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION] Courier-IMAP ready. Copyright 1998-2011 Double Precision, Inc.  See COPYING for distribution information.


     The last line of the output is a greeting from the IMAP server.  Further conversation with the IMAP server will be a series of requests and responses.   Requests are also known as commands and should begin with an arbitrary tag (an alpha numeric string ) followed by a command and its optional arguments, all separated by spaces.  The response, if positive will be the request tag name followed by OK and further by a server message.  This is for a single line response.  If the response is multi line, all except the last line with begin with a "*" and the last line will be request tag followed by OK and then server message.  A negative response will begin with request tag followed by a "NO" and a server message.

     To test the IMAP server at a minimum we should login,select INBOX, retrieve a message and logout.  Let us start by providing a tag followed by the command "login" followed by the IMAP username and password, all separated by spaces.

A01 LOGIN safeer fake_Password
A01 OK LOGIN Ok.


     With IMAP, you can have multiple mailboxes.  "INBOX" is the default and only one mailbox if you have not configured additional mailboxes.  Let us see the mailboxes and its sub folders using list command.  It takes two arguments, first being the folder to list and the second being a search parameter.  Since we are looking for mail boxes, we should be searching the root of the IMAP indicated by a blank "".  The search parameter is a wildcard ( "*" ) here since we want to see all folders under the root.

A02 list "" "*"

* LIST (\Marked \HasNoChildren) "." "INBOX"
1 OK LIST completed


     This is a multi line response from the server and it says there is only one mailbox "INBOX" with no sub folders.  Now let us see the  status of the "INBOX" and find out the number of messages in it.

A03 STATUS INBOX messages
* STATUS "INBOX" (MESSAGES 1)
A03 OK STATUS Completed.


     There is only one message in the INBOX. In order to view messages in the mailbox INBOX ( or any IMAP folder for that matter ) we should first select the folder.

A04 SELECT INBOX
* FLAGS (\Draft \Answered \Flagged \Deleted \Seen \Recent)
* OK [PERMANENTFLAGS (\* \Draft \Answered \Flagged \Deleted \Seen)] Limited
* 1 EXISTS
* 1 RECENT
* OK [UIDVALIDITY 1358664910] Ok
* OK [MYRIGHTS "acdilrsw"] ACL
A04 OK [READ-WRITE] Ok


     In the response, 1 EXISTS means there is only one message in INBOX and 1 RECENT means that 1 message is unread.  We can list/read the emails by using the fetch command.    Let us read the message ( since there is only one message in the INBOX, the id of the message will be 1 and that is passed as an argument to fetch command).  Let us first view the email headers.

A05 FETCH 1 body[header]
* 1 FETCH (BODY[HEADER] {501}
Return-Path: <info@safeer.in>
X-Original-To: safeer@safeer.in
Delivered-To: safeer@smtp.safeer.in
Received: from penguinpower (penguinpower [128.1.0.5])
    by smtp.safeer.in (Postfix) with ESMTP id AD10226089C
    for <safeer@safeer.in>; Thu, 10 Feb 2011 00:42:29 +0530 (IST)
Subject: POP3 Check
Message-Id: <20110210191235.AD10226089C@smtp.safeer.in>
Date: Thu, 10 Feb 2011 00:42:29 +0530 (IST)
From: info@safeer.in

)
* 1 FETCH (FLAGS (\Seen \Recent))
A05 OK FETCH completed.


     You can see the message headers.  Now let us read the message text.

A06 FETCH 1 body[text]
* 1 FETCH (BODY[TEXT] {14}
Testing POP3
)
A06 OK FETCH completed.


     We are done retrieving the message.  Note that fetch command can operate on a single message id or a range or ids in the format START:END.

    Now logout of the session:

A07  LOGOUT
* BYE Courier-IMAP server shutting down
A07 OK LOGOUT completed
Connection closed by foreign host.


    To know more about IMAP checkout the IMAP RFC at ITEF

Friday, December 17, 2010

Configuring Dovecot as a POP3 or IMAP server

     Dovecot can be used to retrieve mail using pop3 or imap protocols.  The minimal configuration that will get you started is pretty simple and straight forward.

First install the package, for RHEL based distros, it is dovecot.

yum install dovecot


The main configuration file for dovecot is /etc/dovecot.conf ( location changes based on you installation, file name remains as dovecot.conf )

## Dovecot supports pop3,pop3s,imap and imaps protocols. 
## Enable whichever you require.
protocols = imap pop3

## If you are using conventional unix style mboxes under
## /var/spool/mail/<username> for storing mail
mail_location = mbox:~/mail:INBOX=/var/spool/mail/%u


That is it, you can start using dovecot sevice.  Edit and save the file and restart service.

sudo /usr/sbin/service dovecot restart

To test if dovecot is working, use instructions from following tutorial

Testing your POP3 server with telnet