作者:hellcoder
项目:streamtool
// getEmails will fetch the full bodies of all emails listed in the given command.
func getEmails(client *imap.Client, cmd *imap.Command) ([]map[string]interface{}, error) {
var emails []map[string]interface{}
seq := new(imap.SeqSet)
for _, rsp := range cmd.Data {
for _, uid := range rsp.SearchResults() {
seq.AddNum(uid)
}
}
if seq.Empty() {
return emails, nil
}
fCmd, err := imap.Wait(client.UIDFetch(seq, "INTERNALDATE", "BODY[]", "UID", "RFC822.HEADER"))
if err != nil {
return emails, err
}
var email map[string]interface{}
for _, msgData := range fCmd.Data {
msgFields := msgData.MessageInfo().Attrs
email, err = newEmailMessage(msgFields)
if err != nil {
return emails, err
}
emails = append(emails, email)
// mark message as read
fSeq := new(imap.SeqSet)
fSeq.AddNum(imap.AsNumber(msgFields["UID"]))
_, err = imap.Wait(client.UIDStore(fSeq, "+FLAGS", "\\SEEN"))
if err != nil {
return emails, err
}
}
return emails, nil
}
作者:ht
项目:imapfeede
func (i *ImapSession) imapCleanup(folders []string) error {
c := i.client
for _, mbox := range folders {
cmd, err := imap.Wait(c.Select(mbox, false))
if err != nil {
fmt.Println("unable to select", mbox, "=>", err, i.client.State())
continue
}
fmt.Println("cleaning up", mbox)
yesterday := time.Now().Add(-1 * 24 * time.Hour)
cmd = imapMust(imap.Wait(c.UIDSearch("SEEN BEFORE " + yesterday.Format("02-Jan-2006") + " NOT FLAGGED")))
toDelete, _ := imap.NewSeqSet("")
toDelete.AddNum(cmd.Data[0].SearchResults()...)
if !toDelete.Empty() {
fmt.Println("deleting...", toDelete)
if i.isGmail {
imapMust(imap.Wait(c.UIDStore(toDelete, "X-GM-LABELS", imap.NewFlagSet(`\Trash`))))
} else {
imapMust(imap.Wait(c.UIDStore(toDelete, "+FLAGS.SILENT", imap.NewFlagSet(`\Deleted`))))
}
imapMust(imap.Wait(c.Expunge(nil)))
}
}
return nil
}
作者:jprobinso
项目:copycat-ima
// checkAndStoreMessages will wait for WorkRequests to come acorss the pipe. When it receives a request, it will search
// the given destination inbox for the message. If it is not found, this method will attempt to pull the messages data
// from fetchRequests and then append it to the destination.
func CheckAndAppendMessages(dstConn *imap.Client, storeRequests chan WorkRequest, fetchRequests chan fetchRequest, wg *sync.WaitGroup) {
defer wg.Done()
// noop it every few to keep things alive
timeout := time.NewTicker(NoopMinutes * time.Minute)
done := false
for {
select {
case request, ok := <-storeRequests:
if !ok {
done = true
break
}
// search for in dst
cmd, err := imap.Wait(dstConn.UIDSearch([]imap.Field{"HEADER", request.Header, request.Value}))
if err != nil {
log.Printf("Unable to search for message (%s): %s. skippin!", request.Value, err.Error())
continue
}
results := cmd.Data[0].SearchResults()
// if not found, PULL from SRC and STORE in DST
if len(results) == 0 {
// only fetch if we dont have data already
if len(request.Msg.Body) == 0 {
// build and send fetch request
response := make(chan MessageData)
fr := fetchRequest{MessageId: request.Value, UID: request.UID, Response: response}
fetchRequests <- fr
// grab response from fetchers
request.Msg = <-response
}
if len(request.Msg.Body) == 0 {
log.Printf("No data found for from fetch request (%s). giving up", request.Value)
continue
}
err = AppendMessage(dstConn, request.Msg)
if err != nil {
log.Printf("Problems appending message to dst: %s. quitting.", err.Error())
return
}
}
case <-timeout.C:
imap.Wait(dstConn.Noop())
}
if done {
break
}
}
log.Print("storer complete!")
return
}
作者:hellcoder
项目:streamtool
// findUnreadEmails will run a find the UIDs of any unread emails in the
// mailbox.
func findUnreadEmails(conn *imap.Client) (*imap.Command, error) {
// get headers and UID for UnSeen message in src inbox...
cmd, err := imap.Wait(conn.UIDSearch("UNSEEN"))
if err != nil {
return &imap.Command{}, err
}
return cmd, nil
}
作者:jprobinso
项目:copycat-ima
func checkMessagesExist(srcConn *imap.Client, checkRequests chan checkExistsRequest, wg *sync.WaitGroup) {
defer wg.Done()
// get memcache client
cache := memcache.New(MemcacheServer)
timeout := time.NewTicker(NoopMinutes * time.Minute)
done := false
for {
select {
case request, ok := <-checkRequests:
if !ok {
done = true
break
}
// check if it exists in src
// search for in src
cmd, err := imap.Wait(srcConn.UIDSearch([]imap.Field{"HEADER", "Message-Id", request.MessageId}))
if err != nil {
log.Printf("Unable to search source: %s", err.Error())
request.Response <- true
continue
}
results := cmd.Data[0].SearchResults()
// if not found, mark for deletion in DST
found := (len(results) > 0)
// response with found bool
request.Response <- found
// if it doesnt exist, attempt to remove it from memcached
if !found {
cache.Delete(request.MessageId)
}
case <-timeout.C:
imap.Wait(srcConn.Noop())
}
if done {
break
}
}
}
作者:jprobinso
项目:copycat-ima
// FetchEmails will sit and wait for fetchRequests from the destination workers.
func fetchEmails(conn *imap.Client, requests chan fetchRequest, cache *Cache) {
// noop every few to keep things alive
timeout := time.NewTicker(NoopMinutes * time.Minute)
done := false
for {
select {
case request, ok := <-requests:
if !ok {
done = true
break
}
found := true
// check if the message body is in cache
data, err := cache.Get(request.MessageId)
if err != nil {
found = false
if err != ErrNotFound {
log.Printf("problems pulling message data from cache: %s. Pulling message from src...", err.Error())
}
data = MessageData{}
}
if found {
log.Print("cache success!")
request.Response <- data
continue
}
msgData, err := FetchMessage(conn, request.UID)
if err != nil {
if err == NotFound {
log.Printf("No data found for UID: %d", request.UID)
} else {
log.Printf("Problems fetching message (%s) data: %s. Passing request and quitting.", request.MessageId, err.Error())
requests <- request
return
}
}
request.Response <- msgData
err = cache.Put(request.MessageId, msgData)
if err != nil {
log.Printf("Unable to add message (%s) to cache: %s", request.MessageId, err.Error())
}
case <-timeout.C:
imap.Wait(conn.Noop())
}
if done {
break
}
}
}
作者:llvt
项目:gomai
func readMessage(message *imap.MessageInfo) {
set := new(imap.SeqSet)
set.AddNum(message.Seq)
cmd, err := imap.Wait(c.Fetch(set, BODY_PART_NAME))
panicMaybe(err)
reader, err := messageReader(cmd.Data[0].MessageInfo())
panicMaybe(err)
scanner := bufio.NewScanner(reader)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
messageBodyStr := strings.Join(lines[:min(len(lines), ui.TermHeight()-2)], "\n")
if len(messageBodyStr) <= 0 {
LOG.Printf("Message body was empty or could not be retrieved: +%v\n", err)
return
}
msgBox := ui.NewPar(messageBodyStr)
msgBox.Border.Label = "Reading Message"
msgBox.Height = ui.TermHeight()
msgBox.Width = ui.TermWidth()
msgBox.Y = 0
ui.Render(msgBox)
topLineIndex := 0
redraw := make(chan bool)
for {
select {
case e := <-ui.EventCh():
switch e.Key {
case ui.KeyArrowDown:
topLineIndex = max(0, min(
len(lines)-msgBox.Height/2,
topLineIndex+1))
go func() { redraw <- true }()
case ui.KeyArrowUp:
topLineIndex = max(0, topLineIndex-1)
go func() { redraw <- true }()
case ui.KeyEsc:
// back to "list messages"
return
}
case <-redraw:
messageBodyStr = strings.Join(lines[topLineIndex+1:], "\n")
msgBox.Text = messageBodyStr
ui.Render(msgBox)
}
}
}
作者:jprobinso
项目:copycat-ima
func GetAllMessages(conn *imap.Client) (*imap.Command, error) {
// get headers and UID for ALL message in src inbox...
allMsgs, _ := imap.NewSeqSet("")
allMsgs.Add("1:*")
cmd, err := imap.Wait(conn.Fetch(allMsgs, "RFC822.HEADER", "UID"))
if err != nil {
return &imap.Command{}, err
}
return cmd, nil
}
作者:jprobinso
项目:copycat-ima
func ResetConnection(conn *imap.Client, readOnly bool) error {
// dont check for error because its possible it's already closed.
conn.Close(!readOnly)
_, err := imap.Wait(conn.Select("INBOX", readOnly))
if err != nil {
return err
}
return nil
}
作者:jprobinso
项目:copycat-ima
func checkAndPurgeMessages(conn *imap.Client, requests chan WorkRequest, checkRequests chan checkExistsRequest, wg *sync.WaitGroup) {
defer wg.Done()
timeout := time.NewTicker(NoopMinutes * time.Minute)
done := false
for {
select {
case request, ok := <-requests:
if !ok {
done = true
break
}
// check and wait for response
response := make(chan bool)
cr := checkExistsRequest{UID: request.UID, MessageId: request.Value, Response: response}
checkRequests <- cr
// if response is false (does not exist), flag as Deleted
if exists := <-response; !exists {
log.Printf("not found in src. marking for deletion: %s", request.Value)
err := AddDeletedFlag(conn, request.UID)
if err != nil {
log.Printf("Problems removing message from dst: %s", err.Error())
}
}
case <-timeout.C:
imap.Wait(conn.Noop())
}
if done {
break
}
}
log.Printf("expunging...")
// expunge at the end
allMsgs, _ := imap.NewSeqSet("")
allMsgs.Add("1:*")
imap.Wait(conn.Expunge(allMsgs))
log.Printf("expunge complete.")
}
作者:ht
项目:imapfeede
func (i *ImapSession) Append(folder string, extraCopies []string, msg io.Reader) error {
c := i.client
mbox := folder
buf := new(bytes.Buffer)
buf.ReadFrom(msg)
now := time.Now()
cmd, err := imap.Wait(c.Append(mbox, nil, &now, imap.NewLiteral(buf.Bytes())))
if err != nil {
fmt.Println(err)
return err
}
rsp, err := cmd.Result(imap.OK)
if err != nil {
fmt.Println(err)
return err
}
uid := imap.AsNumber(rsp.Fields[len(rsp.Fields)-1])
set, _ := imap.NewSeqSet("")
set.AddNum(uid)
imapMust(imap.Wait(c.Select(mbox, false)))
for _, mb := range extraCopies {
if i.isGmail {
imapMust(imap.Wait(c.UIDStore(set, "X-GM-LABELS", imap.NewFlagSet(mb))))
} else {
imapMust(c.UIDCopy(set, mb))
}
}
return nil
}
作者:ht
项目:imapfeede
func (i *ImapSession) CreateFolder(folder string) error {
c := i.client
mbox := folder
if _, err := imap.Wait(c.Create(mbox)); err != nil {
if rsp, ok := err.(imap.ResponseError); ok && rsp.Status == imap.NO {
return nil
} else {
return err
}
}
return nil
}
作者:hellcoder
项目:streamtool
// newIMAPClient will initiate a new IMAP connection with the given creds.
func newIMAPClient(host, username, password, mailbox string) (*imap.Client, error) {
client, err := imap.DialTLS(host, new(tls.Config))
if err != nil {
return client, err
}
_, err = client.Login(username, password)
if err != nil {
return client, err
}
_, err = imap.Wait(client.Select(mailbox, false))
if err != nil {
return client, err
}
return client, nil
}
作者:jprobinso
项目:copycat-ima
func GetConnection(info InboxInfo, readOnly bool) (*imap.Client, error) {
conn, err := imap.DialTLS(info.Host, new(tls.Config))
if err != nil {
return nil, err
}
_, err = conn.Login(info.User, info.Pw)
if err != nil {
return nil, err
}
_, err = imap.Wait(conn.Select("INBOX", readOnly))
if err != nil {
return nil, err
}
return conn, nil
}
作者:jprobinso
项目:copycat-ima
func FetchMessage(conn *imap.Client, messageUID uint32) (msg MessageData, err error) {
seq, _ := imap.NewSeqSet("")
seq.AddNum(messageUID)
var cmd *imap.Command
cmd, err = imap.Wait(conn.UIDFetch(seq, "INTERNALDATE", "BODY[]", "UID", "RFC822.HEADER"))
if err != nil {
log.Printf("Unable to fetch message (%d): %s", messageUID, err.Error())
return
}
if len(cmd.Data) == 0 {
log.Printf("Unable to fetch message (%d) from src: NO DATA", messageUID)
return msg, NotFound
}
msgFields := cmd.Data[0].MessageInfo().Attrs
msg = MessageData{InternalDate: imap.AsDateTime(msgFields["INTERNALDATE"]), Body: imap.AsBytes(msgFields["BODY[]"])}
return msg, nil
}
作者:daffodi
项目:go-mailki
func GetUIDs(mbox string, client *imap.Client) ([]uint32, error) {
uids := make([]uint32, 0)
cmd, err := client.Select(mbox, true)
if err != nil {
return uids, err
}
//== Get UIDS of all messages
cmd, err = imap.Wait(client.UIDSearch("", "ALL"))
if err != nil {
return uids, err
}
for idx := range cmd.Data {
for _, uid := range cmd.Data[idx].SearchResults() {
uids = append(uids, uid)
}
}
return uids, nil
}
作者:jprobinso
项目:copycat-ima
// getNextUID will grab the next message UID from the inbox. Client.Mailbox.UIDNext is cached so we can't use it.
func getNextUID(conn *imap.Client) (uint32, error) {
cmd, err := imap.Wait(conn.Status("INBOX", "UIDNEXT"))
if err != nil {
return 0, err
}
if len(cmd.Data) == 0 {
return 0, errors.New("no data returned!")
}
var status *imap.MailboxStatus
for _, resp := range cmd.Data {
switch resp.Type {
case imap.Data:
status = resp.MailboxStatus()
if status != nil {
break
}
}
}
return status.UIDNext, nil
}
作者:justjak
项目:mai
// geet all the top-level mailboxes in the server, and return them
func (s *Server) GetMailboxes() (boxes []*Mailbox, err error) {
c, err := s.Connect()
if err != nil {
return
}
// fetch data synchronously
cmd, err := imap.Wait(c.List("", "%"))
if err != nil {
return
}
boxes = make([]*Mailbox, len(cmd.Data))
for i, rsp := range cmd.Data {
info := rsp.MailboxInfo()
mbox := NewMailbox(info.Name, s)
boxes[i] = mbox
s.Mailboxes[mbox.Name] = mbox
}
return boxes, nil
}
作者:daffodi
项目:go-mailki
//= Return list of IMAP folders
func GetFolders(client *imap.Client) ([]*Folder, error) {
folders := make([]*Folder, 0)
cmd, err := imap.Wait(client.List("", "*"))
if err != nil {
return folders, err
}
for idx := range cmd.Data {
info := cmd.Data[idx].MailboxInfo()
fol := new(Folder)
fol.Name = info.Name
for flag, boo := range info.Attrs {
fmt.Println(info.Name, boo, flag)
if info.Name == "INBOX" && boo {
fol.Type = "inbox"
} else if flag == "\\Junk" && boo {
fol.Type = "junk"
} else if flag == "\\Trash" && boo {
fol.Type = "trash"
} else if flag == "\\Sent" && boo {
fol.Type = "sent"
} else if flag == "\\Drafts" && boo {
fol.Type = "drafts"
}
}
folders = append(folders, fol)
}
return folders, nil
}
作者:justjak
项目:mai
// messages are usually created with just header information
// this method downloads the actual body of the message from the server,
// optionally marking the message as '\Seen', in IMAP terms.
func (m *Email) Body(setRead bool) (body []byte, err error) {
// cache
if m.bodyData != nil {
return m.bodyData, nil
}
// what will our FETCH request?
var requestType string
if setRead {
requestType = "BODY[TEXT]"
} else {
requestType = "BODY.PEEK[TEXT]"
}
cmd, err := m.RetrieveRaw(requestType)
cmd, err = imap.Wait(cmd, err)
if err != nil {
return
}
info := cmd.Data[0].MessageInfo()
m.bodyData = imap.AsBytes(info.Attrs["BODY[TEXT]"])
return m.bodyData, nil
}