Skip to content

Instantly share code, notes, and snippets.

@anta40
Created September 5, 2023 14:01
Show Gist options
  • Save anta40/42f83dc400ac93ec41c2876f4b26c410 to your computer and use it in GitHub Desktop.
Save anta40/42f83dc400ac93ec41c2876f4b26c410 to your computer and use it in GitHub Desktop.
Scan inbox for emails from a certain sender
package main
import (
"fmt"
"github.com/emersion/go-imap/v2"
"github.com/emersion/go-imap/v2/imapclient"
)
func generateIdRange(startIdx, endIdx uint32) []uint32 {
var x uint32
var theSize = endIdx - startIdx
var theSlice = make([]uint32, theSize)
for x = 0; x < theSize; x++ {
theSlice[x] = startIdx + x
}
return theSlice
}
func main() {
client, client_err := imapclient.DialTLS("xxx.xxx.xxx:993", nil)
if client_err != nil {
fmt.Printf("Failed to dial IMAP server: %v", client_err)
} else {
fmt.Printf("Succesfully connected to IMAP server...\n")
}
defer client.Close()
if client_err := client.Login("xxxxx", "xxxxx).Wait(); client_err != nil {
fmt.Printf("Failed to login: %v", client_err)
} else {
fmt.Printf("Succesfully logged in...\n")
}
mailboxes, client_err := client.List("", "%", nil).Collect()
if client_err != nil {
fmt.Printf("Failed to list mailboxes: %v\n", client_err)
} else {
fmt.Printf("Found %v mailboxes\n", len(mailboxes))
for _, mbox := range mailboxes {
fmt.Printf(" - %v\n", mbox.Mailbox)
}
}
selectedMbox, client_err := client.Select("INBOX", nil).Wait()
if client_err != nil {
fmt.Printf("Failed to select INBOX: %v\n", client_err)
} else {
fmt.Printf("INBOX contains %v messages\n", selectedMbox.NumMessages)
}
if selectedMbox.NumMessages > 0 {
theArr := generateIdRange(1, selectedMbox.NumMessages)
seqSet := imap.SeqSetNum(theArr...)
fetchOptions := &imap.FetchOptions{Envelope: true}
messages, client_err := client.Fetch(seqSet, fetchOptions).Collect()
if client_err != nil {
fmt.Printf("Failed to fetch first message in INBOX: %v\n", client_err)
} else {
fmt.Printf("Message(s) count: %d\n", len(messages))
var x uint32
for x = 0; x < selectedMbox.NumMessages-1; x++ {
var sender = messages[x].Envelope.Sender[0].Mailbox + "@" + messages[x].Envelope.Sender[0].Host
if sender == "[email protected]" {
// OK this is email from [email protected]
// Next step is grab the Excel attachment..... how
}
}
}
}
if err := client.Logout().Wait(); err != nil {
fmt.Printf("Failed to logout: %v\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment