Search code examples
goimap

Golang IMAP: moving messages to another folder


I'm lost on where to look in the references to accomplish this; I've tried several iterations of code and each fails. Slightly edited, but enough to get the gist...

// Make connection
imConnection, err := imap.DialTLS(strAddress, nil)

// Defer disconnect
defer func(){
    imConnection.Logout(30*time.Second)
}

// Authenticate
imConnection.Login(strUname, strPass)

//Select the folder with messages I want to move
imConnection.Select(`[Gmail]\Movethese`, false)

// Create a set
set, _ = imap.NewSeqSet("1:*")

// It's my understanding that moving messages means copying them over, then
// deleting the original messages?
cmd, _ := imConnection.UIDCopy(set, `[Gmail]\Destination`)

This seems to silently fail. This to me looked like it should select everything in the "Movethese" folder and copy them to "Destination." What am I missing in properly copying them over? Is there a simple way to move individual messages that match a certain subject line string?

Also I wasn't sure if the source directory would have to be set to False for R/W when selected, but it doesn't seem to make a difference.

This is importing the github.com/mxk/go-imap/imap package


Solution

  • Try to add error checking to the two commands that name mailboxes; the backslash is a special character in source code so I expect gmail is giving you an error such as No such mailbox: [Gmail]Movethese.

    Handling errors is generally a good idea, particularly in cases such as this, when you know there is an error somewhere.

    BTW, the copy/delete sequence is a bit oldfashioned. Most IMAP servers support UID MOVE as an atomic command these days, and IIRC gmail is among the supporters. Can't check now, though, so don't trust me.