Sample code for 30+ languages & platforms
AutoIt

Fetch an IMAP Attachment into a BinData

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchAttachmentBd method, which stores one attachment's bytes in a BinData object. The first argument is the Email, the second is the zero-based attachment index, and the third is the BinData, which is cleared before the operation. This example fetches the first attachment and prints its byte count.

Background: A BinData holds raw bytes, so it works for any attachment type — image, PDF, zip, and so on. From there you can save it, hash it, or hand it to another API expecting a byte buffer, all without touching the filesystem. Use the string/StringBuilder variants only when the attachment is known to be text.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

;  Demonstrates the Imap.FetchAttachmentBd method, which downloads one attachment's bytes into
;  a BinData object.  The 1st argument is the Email, the 2nd is the zero-based attachment
;  index, and the 3rd is the BinData (which is cleared first).
;  
;  The message is fetched headers-only, then the attachment is downloaded on demand.

$oImap = ObjCreate("Chilkat.Imap")

$oImap.Ssl = True
$oImap.Port = 993

$bSuccess = $oImap.Connect("imap.example.com")
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oImap.Login("user@example.com","myPassword")
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oImap.SelectMailbox("Inbox")
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf

;  Fetch only the message headers.  Attachment bodies are NOT downloaded, but the ckx-imap-*
;  metadata describing the attachments is present, so the attachment info methods still work.
Local $bHeadersOnly = True
Local $bUseUid = False
Local $iSeqNum = 1
$oEmail = ObjCreate("Chilkat.Email")
$bSuccess = $oImap.FetchEmail($bHeadersOnly,$iSeqNum,$bUseUid,$oEmail)
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf

Local $iNumAttach = $oImap.GetMailNumAttach($oEmail)
If ($iNumAttach > 0) Then
    ;  Download just the first attachment's bytes from the server into a BinData.
    $oBd = ObjCreate("Chilkat.BinData")
    $bSuccess = $oImap.FetchAttachmentBd($oEmail,0,$oBd)
    If ($bSuccess = False) Then
        ConsoleWrite($oImap.LastErrorText & @CRLF)
        Exit
    EndIf

    ConsoleWrite("Attachment size: " & $oBd.NumBytes & " bytes" & @CRLF)
EndIf

$bSuccess = $oImap.Disconnect()
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf