examples/Messaging/Imap4Example/imap4example.cpp

Go to the documentation of this file.
00001 // Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
00002 // All rights reserved.
00003 // This component and the accompanying materials are made available
00004 // under the terms of "Eclipse Public License v1.0"
00005 // which accompanies this distribution, and is available
00006 // at the URL "http://www.eclipse.org/legal/epl-v10.html".
00007 //
00008 // Initial Contributors:
00009 // Nokia Corporation - initial contribution.
00010 //
00011 // Contributors:
00012 //
00013 // Description:
00014 // This is a simple code example that demonstrates the use of 
00015 // the IMAP4 protocol to retrieve emails. 
00016 // The code creates a simple SMTP mail, sends it 
00017 // and then retrieves the same using IMAP4.
00018 //
00019 
00020 
00021 
00026 #include "imap4example.h"
00027 #include "asyncwaiter.h"
00028 #include <e32cons.h>
00029 #include "imapset.h"
00030 #include "impcmtm.h"
00031 #include <mtclbase.h>
00032 #include <iapprefs.h>
00033 
00034 _LIT(KTitle, "Imap4example");
00035 _LIT(KTextPressAKey, "\n\n Press any key to step through the example");
00036 _LIT(KExit,"\n\n Press any key to exit the application ");
00037 _LIT(KCreateMtm,"\n\n Creating an IMAP4 client MTM");
00038 _LIT(KTxtAccountName, "ImapAccount");
00039 _LIT(KCreateAccounts,"\n\n Creating IMAP and SMTP acoounts");
00040 _LIT(KSmtpServerAddress, "ban-sindhub01.intra");
00041 _LIT(KEmailAlias, "Messaging example");
00042 _LIT(KSmtpEmailAddress, "ban-sindhub01@ban-sindhub01.intra");
00043 _LIT8(KFrom, "ban-sindhub01@ban-sindhub01.intra");
00044 _LIT(KTo, "ban-sindhub01@ban-sindhub01.intra");
00045 _LIT(KSubject, "SimpleEmail");
00046 _LIT(KBodyContents, "This is a very simple mail");
00047 _LIT(KSendMail,"\n\n Sending the mail ... please wait");
00048 _LIT(KImapServer, "ban-sindhub01.intra");
00049 _LIT8(KImapPassword,"ban-sindhub01");
00050 _LIT8(KImapLoginName,"ban-sindhub01");
00051 _LIT(KWait,"\n\n Connecting to the IMAP server");
00052 _LIT(KPopulate,"\n\n Downloading........");
00053 _LIT(KDisconnect,"\n\n Disconnecting from the IMAP server");
00054 
00059 CImap4Example* CImap4Example::NewL()
00060         {
00061         CImap4Example* self= new (ELeave) CImap4Example();
00062         CleanupStack::PushL(self);
00063         self->ConstructL();
00064         CleanupStack::Pop();
00065         return self;
00066         }
00067 
00071 CImap4Example::CImap4Example()
00072         {}
00073 
00077 void CImap4Example::ConstructL()
00078         {
00079         iConsole = Console::NewL(KTitle,TSize(KConsFullScreen,KConsFullScreen));
00080 
00081         iConsole->Printf ( KTextPressAKey );
00082         iConsole->Getch ();
00083         }
00084 
00088 CImap4Example::~CImap4Example()
00089         {
00090         iConsole->Printf(KExit);
00091         iConsole->Getch();
00092         delete iMtm;
00093         delete iClientRegistry;
00094         delete iSession;
00095         delete iConsole;
00096         }
00097 
00105 void CImap4Example::CreateClientRegistryL()
00106         {
00107         // Create a message server session
00108         iSession=CMsvSession::OpenSyncL(*this);
00109         CleanupStack::PushL(iSession);
00110 
00111         // Create a client-side MTM registry
00112         iClientRegistry=CClientMtmRegistry::NewL(*iSession,KMsvDefaultTimeoutMicroSeconds32);
00113         if (iClientRegistry != NULL && iClientRegistry->IsPresent(KUidMsgTypeIMAP4))
00114                 {
00115                 CleanupStack::PushL(iClientRegistry);
00116                 }
00117         // Create a client-side MTM object for the specified MTM UID.
00118         iMtm=(CImap4ClientMtm*)iClientRegistry->NewMtmL(KUidMsgTypeIMAP4); 
00119         iConsole->Printf(KCreateMtm);
00120         CleanupStack::Pop(2,iSession); // iClientRegistry,iSession
00121         }
00122 
00128 void CImap4Example::CreateImapAndSmtpAccountL()
00129         {
00130         CEmailAccounts* emailAccounts = CEmailAccounts::NewLC();
00131         CImImap4Settings *imap4Settings = new(ELeave)CImImap4Settings;
00132         CleanupStack::PushL(imap4Settings);
00133 
00134         // Add IAP to the IAP preferences
00135         CImIAPPreferences* prefs = CImIAPPreferences::NewLC();
00136         TImIAPChoice iap;
00137         TInt iapID = 0;
00138         CMDBSession* dbSession = CMDBSession::NewL(KCDVersion1_1);
00139         CleanupStack::PushL(dbSession);
00140         CCDConnectionPrefsRecord *connPrefRecord = static_cast<CCDConnectionPrefsRecord*>(CCDRecordBase::RecordFactoryL(KCDTIdConnectionPrefsRecord));
00141         CleanupStack::PushL(connPrefRecord);
00142 
00143         // Set the direction of connection
00144         connPrefRecord->iDirection = ECommDbConnectionDirectionOutgoing;
00145         connPrefRecord->iRanking = 1;
00146         if(!connPrefRecord->FindL(*dbSession))
00147                 {
00148                 User::Leave(KErrNotFound);
00149                 }
00150         iapID = connPrefRecord->iDefaultIAP;
00151         iap.iIAP = iapID;
00152         iap.iDialogPref = ECommDbDialogPrefDoNotPrompt;
00153         prefs->AddIAPL(iap);
00154 
00155         emailAccounts->PopulateDefaultImapSettingsL(*imap4Settings, *prefs);
00156 
00157         // Set the server address to system address
00158         imap4Settings->SetServerAddressL(KImapServer);
00159         imap4Settings->SetLoginNameL(KImapLoginName); 
00160         imap4Settings->SetPasswordL(KImapPassword);
00161         imap4Settings->SetPort(143);
00162 
00163         // Create an IMAP account
00164         iImapAccount = emailAccounts->CreateImapAccountL(KTxtAccountName, *imap4Settings,*prefs,EFalse);
00165 
00166         CImSmtpSettings *smtpSettings = new (ELeave) CImSmtpSettings();
00167         CleanupStack::PushL(smtpSettings);
00168 
00169         emailAccounts->PopulateDefaultSmtpSettingsL(*smtpSettings, *prefs);
00170 
00171         // Create an SMTP acoount
00172         iConsole->Printf(KCreateAccounts);
00173         iSmtpAccount= emailAccounts->CreateSmtpAccountL(iImapAccount, *smtpSettings, *prefs, EFalse);
00174 
00175         emailAccounts->SetDefaultSmtpAccountL(iSmtpAccount);
00176 
00177         smtpSettings->SetServerAddressL(KSmtpServerAddress);
00178         smtpSettings->SetEmailAliasL(KEmailAlias);
00179         smtpSettings->SetEmailAddressL(KSmtpEmailAddress);
00180         smtpSettings->SetReplyToAddressL(KSmtpEmailAddress);
00181         smtpSettings->SetReceiptAddressL(KSmtpEmailAddress);
00182         smtpSettings->SetPort(25);
00183 
00184         emailAccounts->GetSmtpAccountL(iSmtpAccount.iSmtpService, iSmtpAccount);
00185         emailAccounts->SaveSmtpSettingsL(iSmtpAccount,*smtpSettings);
00186         emailAccounts->SaveSmtpIapSettingsL(iSmtpAccount, *prefs);
00187 
00188         CleanupStack::PopAndDestroy(6,emailAccounts); //smtpSettings, connPrefRecord, dbSession, prefs, imap4Settings, emailAccounts
00189         }
00190 
00198 void CImap4Example::CreateSmtpMessageL() 
00199         {
00200         TMsvId outboxId = KMsvGlobalOutBoxIndexEntryId; 
00201 
00202         // Set the context to the folder in which message has to be created
00203         CMsvEntry* entry = CMsvEntry::NewL(*iSession,outboxId,TMsvSelectionOrdering());
00204         CleanupStack::PushL(entry);
00205         entry->SetEntryL(outboxId);
00206 
00207         CMessAsyncWaiter* waiter = CMessAsyncWaiter::NewL();
00208         CleanupStack::PushL(waiter);
00209 
00210         TMsvEmailTypeList msvEmailTypeList = 0;
00211         TMsvPartList partList = (KMsvMessagePartBody | KMsvMessagePartAttachments);
00212 
00213         CImEmailOperation* emailOperation = CImEmailOperation::CreateNewL(waiter->iStatus, *iSession,KMsvGlobalOutBoxIndexEntryId, partList, msvEmailTypeList, KUidMsgTypeSMTP);
00214         CleanupStack::PushL(emailOperation);
00215         waiter->StartAndWait();
00216 
00217         TMsvId temp;
00218         TPckgC<TMsvId> paramPack(temp);
00219         const TDesC8& progBuf = emailOperation->ProgressL();
00220         paramPack.Set(progBuf);
00221         TMsvId newMessageId;
00222         newMessageId = paramPack();
00223 
00224         entry->SetEntryL(newMessageId);
00225 
00226         CMsvStore* store = entry->EditStoreL();
00227         CleanupStack::PushL(store);
00228         CImHeader* emailEntry = CImHeader::NewLC();
00229         emailEntry->RestoreL(*store);
00230         emailEntry->SetFromL((TDesC8&)KFrom);
00231         emailEntry->SetSubjectL((TDesC&)KSubject);
00232         emailEntry->ToRecipients().AppendL((TDesC&)KTo);
00233 
00234         // Paragraph format layer for the rich text object 
00235         CParaFormatLayer* paraFormatLayer = CParaFormatLayer::NewL();
00236         CleanupStack::PushL(paraFormatLayer);
00237         // Character format layer for the rich text object
00238         CCharFormatLayer* charFormatLayer = CCharFormatLayer::NewL(); 
00239         CleanupStack::PushL(charFormatLayer);
00240 
00241         CRichText* bodyText = CRichText::NewL(paraFormatLayer, charFormatLayer, CEditableText::EFlatStorage, 256);
00242         CleanupStack::PushL(bodyText);
00243 
00244         // Insert the contents of a buffer into the document at specified position
00245         bodyText->InsertL(0, KBodyContents);
00246         store->StoreBodyTextL(*bodyText);
00247         emailEntry->StoreL(*store);
00248         // Store the changes permanently
00249         store->CommitL();
00250 
00251         CleanupStack::PopAndDestroy(8,entry); // bodyText,charFormatLayer,paraFormatLayer,emailEntry,store,emailOperation,waiter,entry
00252         }
00253 
00261 void CImap4Example::SendSMTPMessageL()
00262         {
00263         CMsvEntry* entry = iSession->GetEntryL(iSmtpAccount.iSmtpService);
00264         CleanupStack::PushL(entry);
00265 
00266         TMsvId outboxId = KMsvGlobalOutBoxIndexEntryId;
00267 
00268         // Create children selection
00269         TMsvSelectionOrdering order;
00270         order.SetShowInvisibleEntries(ETrue);
00271         entry->SetSortTypeL(order);
00272 
00273         entry->SetEntryL(outboxId);
00274         // Get the  selection containing the IDs of all the context children
00275         CMsvEntrySelection* selection = entry->ChildrenL();
00276 
00277         // Fetch the ID of the first entry
00278         TMsvId entryId = KMsvNullIndexEntryId;
00279         entryId = (*selection)[0];
00280 
00281         delete selection;
00282 
00283         CMessAsyncWaiter* waiter = CMessAsyncWaiter::NewL();
00284         CleanupStack::PushL(waiter);
00285 
00286         iConsole->Printf(KSendMail);
00287         // Create asynchronously copies of children of the context
00288         // as new entries of targetId (smtpServiceId)
00289         CMsvOperation* operation = entry->CopyL(entryId,iSmtpAccount.iSmtpService, waiter->iStatus);
00290 
00291         CleanupStack::PushL(operation);
00292         waiter->StartAndWait();
00293         User::LeaveIfError(waiter->Result());
00294 
00295         CleanupStack::PopAndDestroy(3, entry); // operation,waiter,entry
00296         }
00297 
00308 void CImap4Example::ConnectAndCopyAllMailAndDisconnectL()
00309         {
00310         // Change the current context
00311         iMtm->SwitchCurrentEntryL(iImapAccount.iImapService);
00312         CMsvEntrySelection* selection = new (ELeave) CMsvEntrySelection;
00313         CleanupStack::PushL(selection);
00314 
00315         // Append the imapServiceId onto the end of the array
00316         selection->AppendL(iImapAccount.iImapService);
00317 
00318         TImImap4GetMailInfo imap4GetMailInfo;
00319         imap4GetMailInfo.iMaxEmailSize = KMaxTInt;
00320         imap4GetMailInfo.iDestinationFolder = iImapAccount.iImapService+1; // remote inbox
00321         imap4GetMailInfo.iGetMailBodyParts = EGetImap4EmailBodyText;
00322 
00323         TPckgBuf<TImImap4GetMailInfo> package(imap4GetMailInfo);
00324 
00325         CMessAsyncWaiter* waiter = CMessAsyncWaiter::NewL();
00326         CleanupStack::PushL(waiter);
00327 
00328         // Connect to the server
00329         iConsole->Printf (KWait);
00330         CMsvOperation* operationConnect = iMtm->InvokeAsyncFunctionL(KIMAP4MTMConnect,*selection,package, waiter->iStatus);
00331         CleanupStack::PushL(operationConnect);
00332 
00333         // Wait on the status
00334         waiter->StartAndWait();
00335         User::LeaveIfError(waiter->Result());
00336 
00337         CMsvOperation* operationSync = iMtm->InvokeAsyncFunctionL(KIMAP4MTMFullSync ,*selection,package, waiter->iStatus);
00338         CleanupStack::PushL(operationSync);
00339 
00340         // Wait on the status
00341         waiter->StartAndWait();
00342         User::LeaveIfError(waiter->Result());
00343 
00344         CMsvEntry* entry = iSession->GetEntryL(iImapAccount.iImapService);
00345         CMsvEntrySelection* childrenSelection = entry->ChildrenL();
00346         TMsvId id = (*childrenSelection)[0];
00347         selection->AppendL(id);
00348 
00349         // Copy the meassage when already connected
00350         iConsole->Printf (KPopulate);
00351         CMsvOperation* operationCopy = iMtm->InvokeAsyncFunctionL(KIMAP4MTMPopulateAllMailWhenAlreadyConnected ,*selection,package, waiter->iStatus);
00352         CleanupStack::PushL(operationCopy);
00353 
00354         // Wait on the status
00355         waiter->StartAndWait();
00356 
00357         User::LeaveIfError(waiter->Result());
00358 
00359         // Now disconnect from Imap4 service
00360         iConsole->Printf (KDisconnect);
00361         CMsvOperation* operationDis = iMtm->InvokeAsyncFunctionL(KIMAP4MTMDisconnect,*selection,package, waiter->iStatus);
00362         CleanupStack::PushL(operationDis);
00363 
00364         // Wait on the status
00365         waiter->StartAndWait();
00366         User::LeaveIfError(waiter->Result());
00367         delete entry;
00368         delete childrenSelection;
00369 
00370         CleanupStack::PopAndDestroy(6,selection); // operationDis,operationCopy,operationSync,operationConnect,waiter,selection 
00371         }
00372 
00383 void CImap4Example::HandleSessionEventL(TMsvSessionEvent /*aEvent*/, TAny* /*aArg1*/, TAny* /*aArg2*/, TAny* /*aArg3*/)
00384         {}
00385 
00386 LOCAL_C void MainL()
00387         {
00388         // Create an Active Scheduler to handle asychronous calls
00389         CActiveScheduler* scheduler = new (ELeave) CActiveScheduler;
00390 
00391         // If Active Scheduler has been created, install it.
00392         // As it is an asychronous call we need to install it explicitly.
00393         CActiveScheduler::Install( scheduler );
00394 
00395         CImap4Example* app = CImap4Example::NewL();
00396         CleanupStack::PushL(app);
00397 
00398         // Create a client registry
00399         app->CreateClientRegistryL();
00400 
00401         // Create IMAP and SMTP accounts
00402         app->CreateImapAndSmtpAccountL();
00403 
00404         // Load the physical and logical device drivers.
00405         // Symbian platform will automatically append .PDD and .LDD
00406         TInt err;
00407         err=User::LoadPhysicalDevice(PDD_NAME);
00408         if (err!=KErrNone && err!=KErrAlreadyExists)
00409                 User::Leave(err);
00410         err=User::LoadLogicalDevice(LDD_NAME);
00411         if (err!=KErrNone && err!=KErrAlreadyExists)
00412                 User::Leave(err);
00413 
00414         // Create an SMTP mail to be sent
00415         app->CreateSmtpMessageL();
00416 
00417         // Send the mail created.
00418         app->SendSMTPMessageL();
00419 
00420         // Connect, download and disconnect from the IMAP server
00421         app->ConnectAndCopyAllMailAndDisconnectL();
00422 
00423         CleanupStack::PopAndDestroy(app);
00424 
00425         delete scheduler;
00426         }
00427 
00428 GLDEF_C TInt E32Main()
00429         {
00430         __UHEAP_MARK;
00431         CTrapCleanup* cleanup = CTrapCleanup::New();
00432         if(cleanup == NULL)
00433                 {
00434                 return KErrNoMemory;
00435                 }
00436         TRAPD(err, MainL());
00437         if(err != KErrNone)
00438                 {
00439                 User::Panic(_L("Failed to complete"),err);
00440                 }
00441 
00442         delete cleanup;
00443         __UHEAP_MARKEND;
00444         return KErrNone;
00445         }

Generated on Thu Jan 21 10:32:58 2010 for TB10.1 Example Applications by  doxygen 1.5.3