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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let token = CkoJsonObject()!
success = token.loadFile(path: "gmail-mail-token.json")
if success != true {
print("Could not load the protocol token from the private working directory.")
return
}
if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("Authorize or refresh the mailbox first.")
return
}
var mailbox: String? = "user@example.com"
let imap = CkoImap()!
imap.ssl = true
imap.port = 993
imap.requireSslCertVerify = true
imap.authMethod = "XOAUTH2"
success = imap.connect(hostname: "imap.gmail.com")
if success != true {
print("Could not establish the Gmail IMAP TLS connection.")
return
}
success = imap.login(login: mailbox, password: token.string(of: "access_token"))
if success != true {
imap.disconnect()
print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
return
}
var capabilities: String? = imap.capability()
if (imap.lastMethodSuccess != true) || (imap.hasCapability(name: "X-GM-EXT-1", capabilityResponse: capabilities) != true) {
imap.logout()
imap.disconnect()
print("Gmail IMAP extensions are unavailable.")
return
}
// Choose archive or trash. This example changes one message's location.
var action: String? = "archive"
if (action != "archive") && (action != "trash") {
imap.logout()
imap.disconnect()
print("Choose archive or trash.")
return
}
if imap.hasCapability(name: "MOVE", capabilityResponse: capabilities) != true {
imap.logout()
imap.disconnect()
print("The server must support IMAP MOVE.")
return
}
let folders = CkoMailboxes()!
success = imap.mbxList(subscribed: false, reference: "", mbxPattern: "*", mboxes: folders)
if success != true {
imap.logout()
imap.disconnect()
print("Could not list Gmail folders.")
return
}
var role: String? = "\\All"
if action == "trash" {
role = "\\Trash"
}
var destination: String? = ""
var count: Int = 0
var i: Int = 0
while (i < folders.count.intValue) {
if (folders.hasFlag(index: i, flagName: role) == true) && (folders.isSelectable(index: i) == true) {
destination = folders.getName(index: i)
count = count + 1
}
i = i + 1
}
if count != 1 {
imap.logout()
imap.disconnect()
print("Could not identify the destination folder uniquely.")
return
}
success = imap.selectMailbox(mailbox: "INBOX")
if success != true {
imap.logout()
imap.disconnect()
print("Could not open INBOX for the move.")
return
}
// Obtain this decimal string from the Gmail message/thread ID example.
var gmailMessageId: String? = "1278455344230334865"
let idText = CkoStringBuilder()!
idText.append(value: gmailMessageId)
let validation = CkoJsonObject()!
var matches: Int = idText.regexMatch(pattern: "\\A[1-9][0-9]{0,19}\\z", json: validation, timeoutMs: 1000).intValue
if matches != 1 {
imap.logout()
imap.disconnect()
print("Expected a decimal Gmail message ID string.")
return
}
let target = CkoMessageSet()!
let joined1 = CkoStringBuilder()!
joined1.append(value: "X-GM-MSGID ")
joined1.append(value: gmailMessageId)
success = imap.queryMbx(criteria: joined1.getAsString(), bUid: true, msgSet: target)
if success != true {
imap.logout()
imap.disconnect()
print("Could not find the Gmail message in the selected mailbox.")
return
}
if target.count.intValue != 1 {
imap.logout()
imap.disconnect()
print("Expected one message in the selected mailbox. Matches: \(target.count.intValue)")
return
}
var uid: 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(messageSet: target, destFolder: destination)
if success != true {
imap.logout()
imap.disconnect()
print("Move failed; verify the mailbox state before retrying after a connection loss.")
return
}
print("Completed \(action!) for Gmail message \(gmailMessageId!)")
imap.logout()
imap.disconnect()
}