Skip to content

Instantly share code, notes, and snippets.

@tientp-floware
Last active March 5, 2020 08:47
Show Gist options
  • Save tientp-floware/8bff9aa7aca47fa1cb342bdb28f12136 to your computer and use it in GitHub Desktop.
Save tientp-floware/8bff9aa7aca47fa1cb342bdb28f12136 to your computer and use it in GitHub Desktop.
Email attachment and got body.
package main
import (
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"log"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
"github.com/emersion/go-message/charset"
"github.com/emersion/go-message/mail"
"golang.org/x/text/encoding"
)
func main() {
log.Println("Connecting to server...")
charset.RegisterEncoding("cp-850", encoding.Replacement)
// Connect to server
c, err := client.DialTLS("mail.123floxabccc.com", &tls.Config{InsecureSkipVerify: true})
if err != nil {
log.Fatal(err)
}
log.Println("Connected")
// Don't forget to logout
defer c.Logout()
// Login
if err := c.Login("[email protected]", "supperpassword"); err != nil {
log.Fatal(err)
}
log.Println("Logged in")
// List mailboxes
mailboxes := make(chan *imap.MailboxInfo, 10)
done := make(chan error, 1)
go func() {
done <- c.List("", "*", mailboxes)
}()
log.Println("Mailboxes:")
for m := range mailboxes {
log.Println("* " + m.Name)
}
if err := <-done; err != nil {
log.Fatal(err)
}
// Select INBOX
mbox, err := c.Select("inbox", false)
if err != nil {
log.Fatal(err)
}
log.Println("Flags for Notes:", mbox.Flags)
log.Println("Number:", mbox.Messages)
// Get the last 4 messages
from := uint32(1)
to := mbox.Messages
if mbox.Messages > 3 {
// We're using unsigned integers here, only substract if the result is > 0
//from = mbox.Messages - 3
}
seqset := new(imap.SeqSet)
seqset.AddRange(from, to)
section := &imap.BodySectionName{
/* BodyPartName: imap.BodyPartName{
Specifier: imap.MIMESpecifier,
Fields: []string{"X-Priority", "Priority"},
}, */
}
messages := make(chan *imap.Message, from)
done = make(chan error, 1)
go func() {
done <- c.Fetch(seqset, []imap.FetchItem{section.FetchItem()}, messages)
}()
for msg := range messages {
// Create a new mail reader
mr, err := mail.CreateReader(msg.GetBody(section))
if err != nil {
log.Fatal(err)
}
// Print some info about the message
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 prio := header.Get("X-Priority"); prio != "" {
log.Println("Priority:", prio)
}
if subject, err := header.Subject(); err == nil {
log.Println("Subject:", subject)
}
if conxtdis := header.Get("Content-Disposition"); conxtdis != "" {
log.Println("Content-Disposition:", conxtdis)
}
// Process each message's part
for {
p, err := mr.NextPart()
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
disp := p.Header.Get("Content-Disposition")
switch h := p.Header.(type) {
case *mail.InlineHeader:
// This is the message's text (can be plain-text or HTML)
b, _ := ioutil.ReadAll(p.Body)
if disp != "" {
contentID := h.Get("Content-ID")
_, pr, _ := h.ContentType()
filename := fmt.Sprintf("%s.%s", contentID, pr["name"])
ioutil.WriteFile(filename, b, 0777)
} else {
log.Printf("Got ====: %s", string(b))
}
case *mail.AttachmentHeader:
log.Printf("Got attachment==========")
// This is an attachment
filename, _ := h.Filename()
log.Printf("Got attachment: %v", filename)
b, errp := ioutil.ReadAll(p.Body)
fmt.Println("errp ===== :", errp)
err := ioutil.WriteFile(filename, b, 0777)
if err != nil {
log.Println("attachment err: ", err)
}
}
}
}
if err := <-done; err != nil {
log.Fatal(err)
}
log.Println("Unseen messages:", mbox.Unseen)
log.Println("Done!")
}
@tientp-floware
Copy link
Author

tientp-floware commented Mar 5, 2020

Selection_007

Selection_009

Result output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment