Last active
September 11, 2023 13:11
-
-
Save anta40/9ca67a40da07f40b7a259d1d4d145a0a to your computer and use it in GitHub Desktop.
Read all emails in inbox with go-imap v1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"github.com/emersion/go-imap" | |
"github.com/emersion/go-imap/client" | |
"github.com/emersion/go-message/mail" | |
) | |
func main() { | |
ccc, err := client.DialTLS("imappro.zoho.com:993", nil) | |
if err := ccc.Login("xxxxxxxxxx", "xxxxxxxxxx"); err != nil { | |
fmt.Printf("Failed to login: %v", err) | |
} else { | |
fmt.Printf("Succesfully logged in...\n") | |
} | |
mbox, err := ccc.Select("INBOX", false) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if mbox.Messages == 0 { | |
log.Fatal("No message in mailbox") | |
} else { | |
fmt.Printf("Total message(s) in inbox: %d\n", mbox.Messages) | |
} | |
seqSet := new(imap.SeqSet) | |
seqSet.AddNum(mbox.Messages) | |
var section imap.BodySectionName | |
items := []imap.FetchItem{section.FetchItem()} | |
messages := make(chan *imap.Message, mbox.Messages) | |
go func() { | |
if err := ccc.Fetch(seqSet, items, messages); err != nil { | |
log.Fatal(err) | |
} | |
}() | |
for elem := range messages { | |
if elem == nil { | |
log.Fatal("Server didn't returned message") | |
} | |
r := elem.GetBody(§ion) | |
if r == nil { | |
log.Fatal("Server didn't returned message body") | |
} | |
mr, err := mail.CreateReader(r) | |
if err != nil { | |
log.Fatal(err) | |
} | |
header := mr.Header | |
if date, err := header.Date(); err == nil { | |
log.Println("Date:", date) | |
} | |
if from, err := header.AddressList("From"); err == nil { | |
log.Println("From:", from) | |
} | |
if to, err := header.AddressList("To"); err == nil { | |
log.Println("To:", to) | |
} | |
if subject, err := header.Subject(); err == nil { | |
log.Println("Subject:", subject) | |
} | |
} | |
if err := ccc.Logout(); err != nil { | |
fmt.Printf("Failed to logout: %v\n", err) | |
} | |
} |
keliatannya addNum dipake untuk nentuin index / sequence dari email yang mau dibaca, dia nerima parameter array int, jadi kalau parameternya cuma value dari "mbox.Messages", cuma index / sequence terakhir aja yang dicari.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
knapa milih make addNum daripada addRange?
buffer capacity waktu bikin channel ngaruh dimana?