Skip to content

Instantly share code, notes, and snippets.

@ser1zw
Created June 2, 2014 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ser1zw/dc0157b6a4fcc46fd160 to your computer and use it in GitHub Desktop.
Save ser1zw/dc0157b6a4fcc46fd160 to your computer and use it in GitHub Desktop.
Go IMAP sample
package main
import (
"fmt"
"log"
"os"
"strings"
"time"
"io/ioutil"
"strconv"
"github.com/mxk/go-imap/imap"
)
const (
imapServer = "imap.gmail.com:993"
user = "example@gmail.com"
password = "example"
timeout = 60 * time.Second
)
func main() {
imap.DefaultLogger = log.New(os.Stdout, "", 0)
imap.DefaultLogMask = imap.LogNone
c := Dial(imapServer)
defer func() { execCmd(c.Logout(timeout)) }()
execCmd(c.Noop())
execCmd(Login(c, user, password))
cmd := execCmd(c.List("", "*"))
records := cmd.Data
for i := 0; i < len(records); i++ {
delim := records[i].MailboxInfo().Delim
// mailboxInfo := records[i].MailboxInfo()
// fmt.Printf("[%d]\t%s\t%s\n", i, mailboxInfo.Attrs, mailboxInfo.Name)
encodedPath := imap.AsString(records[i].Fields[3])
// fmt.Printf("[%d]\t%s\t%s\n", i, delim, encodedPath)
folders := strings.Split(strings.Trim(encodedPath, "\""), delim)
for n := 0; n < len(folders); n++ {
decodedName, err := imap.UTF7Decode(folders[n])
if err != nil {
fmt.Println("DOCODE ERROR")
} else {
folders[n] = decodedName
}
}
fmt.Printf("[%d]\t%s\n", i, strings.Join(folders, " / "))
// cmd = execCmd(c.Select(encodedPath, false))
}
cmd = execCmd(c.Select("INBOX", false))
// fmt.Println(c.Mailbox)
set, _ := imap.NewSeqSet("1:*")
// cmd = execCmd(c.Fetch(set, "BODY[]"))
cmd = execCmd(imap.Wait(c.Fetch(set, "BODY[]")))
records = cmd.Data
for i := 0; i < len(records); i++ {
// fmt.Println(imap.AsString(records[i].Fields[0]))
fmt.Println(records[i].Type)
// msgInfo := records[i].MessageInfo
data := imap.AsBytes(records[i].Literals[0])
// fmt.Println(data)
ioutil.WriteFile(strconv.Itoa(i) + ".txt", data, 0777)
}
}
func Dial(addr string) (c *imap.Client) {
var err error
if strings.HasSuffix(addr, ":993") {
c, err = imap.DialTLS(addr, nil)
} else {
c, err = imap.Dial(addr)
}
if err != nil {
panic(err)
}
return c
}
func Login(c *imap.Client, user, pass string) (cmd *imap.Command, err error) {
defer c.SetLogMask(Sensitive(c, "LOGIN"))
return c.Login(user, pass)
}
func Sensitive(c *imap.Client, action string) imap.LogMask {
mask := c.SetLogMask(imap.LogConn)
hide := imap.LogCmd | imap.LogRaw
if mask & hide != 0 {
c.Logln(imap.LogConn, "Raw logging disabled during", action)
}
c.SetLogMask(mask & ^hide)
return mask
}
func execCmd(cmd *imap.Command, err error) *imap.Command {
if cmd == nil || err != nil {
panic(err)
}
_, err = cmd.Result(imap.OK)
if err != nil {
panic(err)
}
return cmd
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment