Unicode C++
Unicode C++
Scan for Emails with Attachments and Save Attachments to Files
Scan for emails with attachments and save attachments.Chilkat Unicode C++ Downloads
#include <CkImapW.h>
#include <CkMessageSetW.h>
#include <CkEmailBundleW.h>
#include <CkEmailW.h>
void ChilkatSample(void)
{
bool success = false;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
CkImapW imap;
// Connect to an IMAP server.
// Use TLS
imap.put_Ssl(true);
imap.put_Port(993);
success = imap.Connect(L"imap.example.com");
if (success == false) {
wprintf(L"%s\n",imap.lastErrorText());
return;
}
// Login
success = imap.Login(L"myLogin",L"myPassword");
if (success == false) {
wprintf(L"%s\n",imap.lastErrorText());
return;
}
// Select an IMAP mailbox
success = imap.SelectMailbox(L"Inbox");
if (success == false) {
wprintf(L"%s\n",imap.lastErrorText());
return;
}
// We can choose to fetch UIDs or sequence numbers.
bool fetchUids = true;
// Get the message IDs of all the emails in the mailbox
CkMessageSetW messageSet;
success = imap.QueryMbx(L"ALL",fetchUids,messageSet);
if (success == false) {
wprintf(L"%s\n",imap.lastErrorText());
return;
}
// Fetch the email headers into a bundle object:
CkEmailBundleW bundle;
bool headersOnly = true;
success = imap.FetchMsgSet(headersOnly,messageSet,bundle);
if (success == false) {
wprintf(L"%s\n",imap.lastErrorText());
return;
}
// Scan for emails with attachments, and save the attachments
// to a sub-directory.
CkEmailW fullEmail;
CkEmailW emailHeader;
int i = 0;
while (i < bundle.get_MessageCount()) {
// The bundle contains email headers..
bundle.EmailAt(i,emailHeader);
// Does this email have attachments?
// Use GetMailNumAttach because the attachments
// are not actually in the email object because
// we only downloaded headers.
int numAttach = imap.GetMailNumAttach(emailHeader);
if (numAttach > 0) {
// Download the entire email and save the
// attachments. (Remember, we
// need to download the entire email because
// only the headers were previously downloaded.
// The ckx-imap-uid header field is added when
// headers are downloaded. This makes it possible
// to get the UID from the email object.
const wchar_t *uidStr = emailHeader.getHeaderField(L"ckx-imap-uid");
int uid = wcstol(uidStr);
success = imap.FetchEmail(false,uid,true,fullEmail);
if (success == false) {
wprintf(L"%s\n",imap.lastErrorText());
return;
}
success = fullEmail.SaveAllAttachments(L"attachmentsDir");
int j;
for (j = 0; j <= numAttach - 1; j++) {
const wchar_t *filename = imap.getMailAttachFilename(emailHeader,j);
wprintf(L"%s\n",filename);
}
}
i = i + 1;
}
// Disconnect from the IMAP server.
success = imap.Disconnect();
}