Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Options
Go to last post Go to first unread
ivan  
#1 Posted : Monday, May 2, 2011 5:06:02 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,154

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Visual C++ Example

If you want to leave a copy of email on the server, you should not call Delete method. However, there is a problem, how can you know if the email has already been downloaded (read)? If there is a way to identify the downloaded email, you can avoid downloading the duplicated email from your POP3/IMAP4 server.

Every email has a unique identifier (UIDL) on POP3 server. POP3 UIDL is only unique in the email life time. That means if the email was deleted from the server, other email can use the old unique identifier. Another problem is: UIDL in POP3 server can be any number or characters, so we cannot use UIDL as the file name, because UIDL may contain invalid characters for file name.

To solve this problem, we have to store the UIDL to a txt file and synchronize it with server every time.

The following example codes demonstrate how to mark the email as downloaded/read on POP3 server.

Code:

// The following example codes demonstrate marking email as read/downloaded on POP3 server
// To get full sample projects, please download and install EAGetMail on your machine.
// To run it correctly, please change email server, user, password, folder, file name value to yours

#include "stdafx.h" 
#include <atlbase.h> 
#include <atlcom.h> 
#include <atlstr.h> 

#include "eagetmailobj.tlh" 
using namespace EAGetMailObjLib; 

class MyClient 
{ 
public: 
    MyClient() 
    { 
        m_uidlfile = _T("uidl.txt"); 

        TCHAR szFile[MAX_PATH+1]; 
        memset( szFile, 0, sizeof(szFile)); 
        ::GetModuleFileName( NULL, szFile, MAX_PATH ); 
        LPCTSTR pszBuf = _tcsrchr( szFile, _T(' ') ); 
        if( pszBuf != NULL ) 
        { 
            m_curpath.Append( szFile, pszBuf - szFile ); 
        } 
        else 
        {/*impossible*/ 
            m_curpath.Append( szFile ); 
        } 
    } 

public: 
    void ReceiveMail( IMailServerPtr &oServer, bool leaveCopy ) 
    { 
        try 
        { 
            CString mailFolder; 
            mailFolder.Format( _T("%s\\inbox"), m_curpath.GetString()); 
            ::CreateDirectory( mailFolder.GetString(), NULL ); 

            IMailClientPtr oClient = NULL; 
            oClient.CreateInstance("EAGetMailObj.MailClient"); 
            oClient->LicenseCode = _T("TryIt"); 

            // uidl is the identifier of every email on POP3/IMAP4 server, to avoid retrieve
            // the same email from server more than once, we record the email uidl retrieved every time
            // if you delete the email from server every time and not to leave a copy of email on
            // the server, then please remove all the function about uidl.
            _LoadUIDL(); 

            oClient->Connect( oServer ); 
            _tprintf(_T("Connected\r\n")); 

            _variant_t arInfo = oClient->GetMailInfos(); 

            _SyncUIDL( oServer, arInfo ); 

            SAFEARRAY *psa = arInfo.parray; 

            long LBound = 0, UBound = 0; 
            SafeArrayGetLBound( psa, 1, &LBound ); 
            SafeArrayGetUBound( psa, 1, &UBound ); 

            INT count = UBound-LBound+1; 
            _tprintf(_T("Total %d email(s)\r\n"), count ); 

            for( long i = LBound; i <= UBound; i++ ) 
            { 
                _variant_t vtInfo; 
                SafeArrayGetElement( psa, &i, &vtInfo ); 

                IMailInfoPtr pInfo; 
                vtInfo.pdispVal->QueryInterface(__uuidof(IMailInfo), (void**)&pInfo); 

                if(_FindExistedUIDL( oServer, pInfo->UIDL )) 
                { 
                    // this email has been downloaded, do not retrieve it again.
                    continue; 
                } 

                IMailPtr oMail = oClient->GetMail(pInfo); 

                // Generate an unique file named based on current date time
                // If you don't like it, you can use your method to generate file name
                CString fileName; 
                SYSTEMTIME curtm; 
                ::GetLocalTime( &curtm ); 
                fileName.Format( _T("%04d%02d%02d%02d%02d%02d%03d%d.eml"), 
                    curtm.wYear, 
                    curtm.wMonth, 
                    curtm.wDay, 
                    curtm.wHour, 
                    curtm.wMinute, 
                    curtm.wSecond, 
                    curtm.wMilliseconds, 
                    i ); 

                CString full = mailFolder; 
                full.Append( _T(\\")); 
                full.Append( fileName ); 
                oMail->SaveAs( full.GetString(), VARIANT_TRUE ); 

                oMail.Release(); 

                if( leaveCopy ) 
                { 
                    // add the email uidl to uidl file to avoid we retrieve it next time.
                    _AddUIDL( oServer, pInfo->UIDL ); 
                } 
            } 

            if( !leaveCopy ) 
            { 
                _tprintf( _T("Deleting ...")); 
                for( long i = LBound; i <= UBound; i++) 
                { 
                    _variant_t vtInfo; 
                    SafeArrayGetElement( psa, &i, &vtInfo ); 

                    IMailInfoPtr pInfo; 
                    vtInfo.pdispVal->QueryInterface(__uuidof(IMailInfo), (void**)&pInfo); 
                    oClient->Delete( pInfo ); 
                } 
            } 

            // Delete method just mark the email as deleted,
            // Quit method pure the emails from server exactly.
            arInfo.Clear(); 
            oClient->Quit(); 
            _tprintf( _T("Completed")); 
        } 
        catch( _com_error &ep ) 
        { 
            _tprintf( _T("Error: %s\r\n"), (const TCHAR*)ep.Description()); 
        } 

        //update the uidl list to a text file and then we can load it next time.
        _UpdateUIDL(); 
    } 

private: 
// uidl is the identifier of every email on POP3/IMAP4 server, to avoid retrieve
// the same email from server more than once, we record the email uidl retrieved every time
// if you delete the email from server every time and not to leave a copy of email on
// the server, then please remove all the function about uidl.
    bool _FindUIDL( _variant_t &infos, LPCTSTR lpszUidl ) 
    { 
        SAFEARRAY *psa = infos.parray; 
        long LBound = 0, UBound = 0; 
        SafeArrayGetLBound( psa, 1, &LBound ); 
        SafeArrayGetUBound( psa, 1, &UBound ); 

        for( long i = LBound; i <= UBound; i++ ) 
        { 
            IMailInfoPtr pInfo; 
            _variant_t vtInfo; 
            SafeArrayGetElement( psa, &i, &vtInfo ); 
            vtInfo.pdispVal->QueryInterface( __uuidof(IMailInfo), (void**)&pInfo); 
            INT t = _tcscmp( pInfo->UIDL, lpszUidl ); 
            if( t == 0 ) 
            { 
                return true; 
            } 
        } 

        return false; 
    } 

    void _SyncUIDL( IMailServerPtr &oServer, _variant_t &infos ) 
    { 
        CString s; 
        s = (TCHAR*)oServer->Server; 
        s += _T("#"); 
        s += (TCHAR*)oServer->User; 
        s += _T(" "); 
        s = s.MakeLower(); 
        bool bcontinue = false; 
        int n = 0; 
        do 
        { 
            bcontinue = false; 
            int count = m_arUidl.GetSize(); 
            for( int i = n; i < count; i++ ) 
            { 
                CString x = m_arUidl[i]; 
                if( _tcsncmp( x.GetString(), s.GetString(), s.GetLength()) == 0 ) 
                { 
                    int pos = x.ReverseFind( _T( ' ' )); 
                    if( pos != -1 ) 
                    { 
                        CString uidl; 
                        uidl = x.Mid( pos + 1 ); 
                        if(!_FindUIDL( infos, uidl.GetString())) 
                        { 
                            // this uidl doesn't exist on server,
                            // so we should remove it from local uidl list to save the storage.
                            bcontinue = true; 
                            n = i; 
                            m_arUidl.RemoveAt(i); 
                            break; 
                        } 
                    } 
                } 
            } 
        }while( bcontinue ); 
    } 

    bool _FindExistedUIDL( IMailServerPtr &oServer, LPCTSTR lpszUidl ) 
    { 
        CString s; 
        s = (TCHAR*)oServer->Server; 
        s += _T("#"); 
        s += (TCHAR*)oServer->User; 
        s += _T(" "); 
        s = s.MakeLower(); 
        s += lpszUidl; 

        int count = m_arUidl.GetSize(); 
        for( int i = 0; i < count; i++ ) 
        { 
            CString x = m_arUidl[i]; 
            if( x.Compare( s ) == 0 ) 
                return true; 
        } 
        return false; 
    } 
    void _AddUIDL( IMailServerPtr &oServer, LPCTSTR lpszUidl ) 
    { 
        CString s; 
        s = (TCHAR*)oServer->Server; 
        s += _T("#"); 
        s += (TCHAR*)oServer->User; 
        s = s.MakeLower(); 
        s += _T(" "); 
        s += lpszUidl; 
        m_arUidl.Add( s ); 
    } 

    void _UpdateUIDL() 
    { 
        CString s; 
        int count = m_arUidl.GetSize(); 
        s.Preallocate( count * 256 ); 

        for( int i = 0; i < count; i++ ) 
        { 
            s.Append( m_arUidl[i] ); 
            s.Append( _T("\r\n")); 
        } 

        CString file; 
        file.Format( _T("%s\\%s"), m_curpath.GetString(), m_uidlfile.GetString() ); 

        IToolsPtr oTool; 
        oTool.CreateInstance( "EAGetMailObj.Tools"); 
        oTool->WriteTextFile( file.GetString(), s.GetString(), CP_UTF8 ); 
        oTool.Release(); 
    } 

    void _LoadUIDL() 
    { 
        m_arUidl.RemoveAll(); 

        IToolsPtr oTool; 
        oTool.CreateInstance( "EAGetMailObj.Tools"); 
        CString file; 
        file.Format( _T("%s\\%s"), m_curpath.GetString(), m_uidlfile.GetString()); 

        CString s; 
        try 
        { 
            s = (TCHAR*)oTool->ReadTextFile( file.GetString(), CP_UTF8 ); 
        } 
        catch( _com_error &ep ) 
        { 
        } 

        oTool.Release(); 

        int curPos = 0; 
        CString resToken= s.Tokenize(_T("\n"),curPos); 
        while (resToken != _T("")) 
        { 
            resToken = resToken.Trim( _T("\r\n \t")); 
            if( resToken.GetLength() > 0 ) 
            { 
                m_arUidl.Add( resToken ); 
            } 
            resToken = s.Tokenize(_T("\n"), curPos); 
        } 
    } 

    CString m_uidlfile; 
    CString m_curpath; 
    CSimpleArray<CString> m_arUidl; 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    const int MailServerPop3 = 0; 
    const int MailServerImap4 = 1; 

    // Initialize COM environment
    ::CoInitialize( NULL ); 

    // Create a folder named "inbox" under current exe file directory
    // to save the emails retrieved.
    TCHAR szPath[MAX_PATH+1]; 
    memset( szPath, 0, sizeof(szPath)); 
    ::GetModuleFileName( NULL, szPath, MAX_PATH ); 

    // Change file name to current full path
    LPCTSTR psz = _tcsrchr( szPath, _T(' ')); 
    if( psz != NULL ) 
    { 
        szPath[psz-szPath] = _T(' 0'); 
    } 
    TCHAR szMailBox[MAX_PATH+1]; 
    memset( szMailBox, 0, sizeof(szMailBox)); 
    wsprintf( szMailBox, _T("%s\\inbox"), szPath ); 

    // Create a folder to store emails
    ::CreateDirectory( szMailBox, NULL ); 

    try 
    { 
        IMailServerPtr oServer = NULL; 
        oServer.CreateInstance("EAGetMailObj.MailServer"); 
        oServer->Server = _T("pop3.emailarchitect.net"); 
        oServer->User = _T("test@emailarchitect.net"); 
        oServer->Password = _T("testpassword"); 
        oServer->Protocol = MailServerPop3; 

        // If your POP3 requires SSL connection
        // Please add the following codes
        // oServer->SSLConnection = VARIANT_TRUE;
        // oServer->Port = 995;

        MyClient client; 
        client.ReceiveMail( oServer, true ); 

    } 
    catch( _com_error &ep ) 
    { 
        _tprintf( _T("Error: %s"), (const TCHAR*)ep.Description()); 
    } 

    return 0; 
} 

Click here to read original topic - full version ...

If you have any comments or questions about above example codes, please add your comments here.
Users browsing this topic
Guest
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Powered by YAF.NET | YAF.NET © 2003-2024, Yet Another Forum.NET
This page was generated in 0.113 seconds.

EXPLORE TUTORIALS

© All Rights Reserved, AIFEI Software Limited & AdminSystem Software Limited.