Lianja
Lianja
Scan for Emails with Attachments and Save Attachments to Files
Scan for emails with attachments and save attachments.Chilkat Lianja Downloads
llSuccess = .F.
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
loImap = createobject("CkImap")
// Connect to an IMAP server.
// Use TLS
loImap.Ssl = .T.
loImap.Port = 993
llSuccess = loImap.Connect("imap.example.com")
if (llSuccess = .F.) then
? loImap.LastErrorText
release loImap
return
endif
// Login
llSuccess = loImap.Login("myLogin","myPassword")
if (llSuccess = .F.) then
? loImap.LastErrorText
release loImap
return
endif
// Select an IMAP mailbox
llSuccess = loImap.SelectMailbox("Inbox")
if (llSuccess = .F.) then
? loImap.LastErrorText
release loImap
return
endif
// We can choose to fetch UIDs or sequence numbers.
llFetchUids = .T.
// Get the message IDs of all the emails in the mailbox
loMessageSet = createobject("CkMessageSet")
llSuccess = loImap.QueryMbx("ALL",llFetchUids,loMessageSet)
if (llSuccess = .F.) then
? loImap.LastErrorText
release loImap
release loMessageSet
return
endif
// Fetch the email headers into a bundle object:
loBundle = createobject("CkEmailBundle")
llHeadersOnly = .T.
llSuccess = loImap.FetchMsgSet(llHeadersOnly,loMessageSet,loBundle)
if (llSuccess = .F.) then
? loImap.LastErrorText
release loImap
release loMessageSet
release loBundle
return
endif
// Scan for emails with attachments, and save the attachments
// to a sub-directory.
loFullEmail = createobject("CkEmail")
loEmailHeader = createobject("CkEmail")
i = 0
do while i < loBundle.MessageCount
// The bundle contains email headers..
loBundle.EmailAt(i,loEmailHeader)
// Does this email have attachments?
// Use GetMailNumAttach because the attachments
// are not actually in the email object because
// we only downloaded headers.
lnNumAttach = loImap.GetMailNumAttach(loEmailHeader)
if (lnNumAttach > 0) then
// 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.
lcUidStr = loEmailHeader.GetHeaderField("ckx-imap-uid")
lnUid = val(lcUidStr)
llSuccess = loImap.FetchEmail(.F.,lnUid,.T.,loFullEmail)
if (llSuccess = .F.) then
? loImap.LastErrorText
release loImap
release loMessageSet
release loBundle
release loFullEmail
release loEmailHeader
return
endif
llSuccess = loFullEmail.SaveAllAttachments("attachmentsDir")
for j = 0 to lnNumAttach - 1
lcFilename = loImap.GetMailAttachFilename(loEmailHeader,j)
? lcFilename
next
endif
i = i + 1
enddo
// Disconnect from the IMAP server.
llSuccess = loImap.Disconnect()
release loImap
release loMessageSet
release loBundle
release loFullEmail
release loEmailHeader