Gmail IMAP: Archive a Message or Move It to Trash
See more GMail SMTP/IMAP/POP Examples
This example changes one message in INBOX. Choose archive to move it to the discovered All Mail folder, or trash to move it to the discovered Trash folder. It resolves a decimal Gmail message ID to a mailbox UID and uses MoveMessages with the server's MOVE capability.
Archiving removes a message from INBOX while retaining it in All Mail. Moving it to Trash is a different action; Gmail normally permanently deletes messages after 30 days there. This example does not empty Trash or permanently delete mail. A message can retain other custom labels when archived.
Folder names are discovered by special-use attributes. Avoid a generic delete/EXPUNGE sequence whose Gmail outcome can depend on account settings and which can affect unrelated messages. If a connection fails during a move, inspect the source and destination before retrying. A concurrent move or deletion can make the UID disappear.
Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.
Chilkat B4X Downloads
Dim success As Boolean = False
' Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim token As ChilkatJsonObject
token.Initialize
success = token.LoadFile("gmail-mail-token.json")
If success <> True Then
Log("Could not load the protocol token from the private working directory.")
Return
End If
If (token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token", "", True) = True) Then
Log("Authorize or refresh the mailbox first.")
Return
End If
Dim mailbox As String = "user@example.com"
Dim imap As ChilkatImap
imap.Initialize("imap")
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If success <> True Then
Log("Could not establish the Gmail IMAP TLS connection.")
Return
End If
success = imap.Login(mailbox, token.StringOf("access_token"))
If success <> True Then
imap.Disconnect
Log("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
Return
End If
Dim capabilities As String = imap.Capability
If (imap.LastMethodSuccess <> True) Or (imap.HasCapability("X-GM-EXT-1", capabilities) <> True) Then
imap.Logout
imap.Disconnect
Log("Gmail IMAP extensions are unavailable.")
Return
End If
' Choose archive or trash. This example changes one message's location.
Dim action As String = "archive"
If (action <> "archive") And (action <> "trash") Then
imap.Logout
imap.Disconnect
Log("Choose archive or trash.")
Return
End If
If imap.HasCapability("MOVE", capabilities) <> True Then
imap.Logout
imap.Disconnect
Log("The server must support IMAP MOVE.")
Return
End If
Dim folders As ChilkatMailboxes
folders.Initialize
success = imap.MbxList(False, "", "*", folders)
If success <> True Then
imap.Logout
imap.Disconnect
Log("Could not list Gmail folders.")
Return
End If
Dim role As String = "\All"
If action = "trash" Then
role = "\Trash"
End If
Dim destination As String = ""
Dim count As Int = 0
Dim i As Int = 0
Do While (i < folders.Count)
If (folders.HasFlag(i, role) = True) And (folders.IsSelectable(i) = True) Then
destination = folders.GetName(i)
count = count + 1
End If
i = i + 1
Loop
If count <> 1 Then
imap.Logout
imap.Disconnect
Log("Could not identify the destination folder uniquely.")
Return
End If
success = imap.SelectMailbox("INBOX")
If success <> True Then
imap.Logout
imap.Disconnect
Log("Could not open INBOX for the move.")
Return
End If
' Obtain this decimal string from the Gmail message/thread ID example.
Dim gmailMessageId As String = "1278455344230334865"
Dim idText As ChilkatStringBuilder
idText.Initialize
idText.Append(gmailMessageId)
Dim validation As ChilkatJsonObject
validation.Initialize
Dim matches As Int = idText.RegexMatch("\A[1-9][0-9]{0,19}\z", validation, 1000)
If matches <> 1 Then
imap.Logout
imap.Disconnect
Log("Expected a decimal Gmail message ID string.")
Return
End If
Dim target As ChilkatMessageSet
target.Initialize
Dim joined1 As ChilkatStringBuilder
joined1.Initialize
joined1.Append("X-GM-MSGID ")
joined1.Append(gmailMessageId)
success = imap.QueryMbx(joined1.GetAsString, True, target)
If success <> True Then
imap.Logout
imap.Disconnect
Log("Could not find the Gmail message in the selected mailbox.")
Return
End If
If target.Count <> 1 Then
imap.Logout
imap.Disconnect
Log("Expected one message in the selected mailbox. Matches: " & target.Count)
Return
End If
Dim uid As String = target.ToCompactString
' MoveMessages uses UID MOVE and maintains the Imap object's mailbox state.
' No broad EXPUNGE is issued, and unrelated deleted flags are not committed.
success = imap.MoveMessages(target, destination)
If success <> True Then
imap.Logout
imap.Disconnect
Log("Move failed; verify the mailbox state before retrying after a connection loss.")
Return
End If
Log("Completed " & action & " for Gmail message " & gmailMessageId)
imap.Logout
imap.Disconnect