package maildir import ( "bufio" "fmt" "io" "mime" "net/mail" "github.com/emersion/go-maildir" ) // A lot of this code was borrowed from aerc/worker/maildir/message.go type Message struct { Dir maildir.Dir Key string } func (m Message) NewReader() (io.Reader, error) { f, err := m.Dir.Open(m.Key) if err != nil { return nil, err } return bufio.NewReader(f), nil } // Flags fetches the set of flags currently applied to the message. func (m Message) Flags() ([]maildir.Flag, error) { return m.Dir.Flags(m.Key) } // SetFlags replaces the message's flags with a new set. func (m Message) SetFlags(flags []maildir.Flag) error { return m.Dir.SetFlags(m.Key, flags) } // SetOneFlag enables or disables a single message flag on the message. func (m Message) SetOneFlag(flag maildir.Flag, enable bool) error { flags, err := m.Flags() if err != nil { return fmt.Errorf("error: could not read previous flags: %v", err) } if enable { flags = append(flags, flag) return m.SetFlags(flags) } var newFlags []maildir.Flag for _, oldFlag := range flags { if oldFlag != flag { newFlags = append(newFlags, oldFlag) } } return m.SetFlags(newFlags) } // MarkReplied either adds or removes the maildir.FlagReplied flag from the // message. func (m Message) MarkReplied(answered bool) error { return m.SetOneFlag(maildir.FlagReplied, answered) } // Remove deletes the email immediately. func (m Message) Remove() error { return m.Dir.Remove(m.Key) } func decodeMime(str string) (string, error) { dec := new(mime.WordDecoder) return dec.DecodeHeader(str) } func (m Message) GetHeader(h string) (string, error) { r, err := m.NewReader() msg, err := mail.ReadMessage(r) if err != nil { return "", err } decodedHeader, err := decodeMime(msg.Header.Get(h)) return decodedHeader, err } var FlagMap = map[maildir.Flag]string{ maildir.FlagDraft: "D", maildir.FlagSeen: "S", maildir.FlagReplied: "R", maildir.FlagTrashed: "T", }