How to use delete method of imap Package

Best Venom code snippet using imap.delete

gmail.go

Source:gmail.go Github

copy

Full Screen

...31 {"f", 1, fcmd, tfcmd, "f forward message"},32 {"h", 0, hcmd, nil, "h print elided message summary (,h for all)"},33 {"help", 0, nil, nil, "help print this info"},34 {"i", 0, icmd, nil, "i incorporate new mail"},35 {"m", 0, mcmd, tmcmd, "m mute and delete thread (gmail only)"},36 {"mime", 0, mimecmd, nil, "mime print message's MIME structure "},37 {"p", 0, pcmd, nil, "p print the processed message"},38 // { "p+", 0, pcmd, nil, "p print the processed message, showing all quoted text" },39 {"P", 0, Pcmd, nil, "P print the raw message"},40 {`"`, 0, quotecmd, nil, `" print a quoted version of msg`},41 {"q", 0, qcmd, nil, "q exit and remove all deleted mail"},42 {"r", 1, rcmd, nil, "r [addr] reply to sender plus any addrs specified"},43 {"s", 1, scmd, tscmd, "s name copy message to named mailbox (label for gmail)"},44 {"u", 0, ucmd, nil, "u remove deletion mark"},45 // { "w", 1, wcmd, nil, "w file store message contents as file" },46 {"W", 0, Wcmd, nil, "W open in web browser"},47 {"x", 0, xcmd, nil, "x exit without flushing deleted messages"},48 {"y", 0, ycmd, nil, "y synchronize with mail box"},49 {"=", 1, eqcmd, nil, "= print current message number"},50 {"|", 1, pipecmd, nil, "|cmd pipe message body to a command"},51 // { "||", 1, rpipecmd, nil, "||cmd pipe raw message to a command" },52 {"!", 1, bangcmd, nil, "!cmd run a command"},53}54func init() {55 // Have to insert helpcmd by hand because it refers to cmdtab,56 // so it would cause an init loop above.57 for i := range cmdtab {58 if cmdtab[i].Name == "help" {59 cmdtab[i].F = helpcmd60 }61 }62}63type Cmd struct {64 Name string65 Args []string66 Line string // Args[0:] original text67 ArgLine string // Args[1:] original text68 F func(*Cmd, *imap.MsgPart) *imap.MsgPart69 TF func(*Cmd, []*imap.Msg) *imap.MsgPart70 Delete bool71 Thread bool72 Targ *imap.MsgPart73 Targs []*imap.Msg74 A1, A2 int75}76var (77 bin = bufio.NewReader(os.Stdin)78 bout = bufio.NewWriter(os.Stdout)79 acctName = flag.String("a", "", "account to use")80 dot *imap.MsgPart // Selected messages81 inbox *imap.Box82 msgs []*imap.Msg83 msgNum = make(map[*imap.Msg]int)84 deleted = make(map[*imap.Msg]bool)85 isGmail = false86 acct google.Account87 threaded bool88 interrupted bool89 maxfrom int90 subjlen int91)92func nextMsg(m *imap.Msg) *imap.Msg {93 i := msgNum[m]94 i++95 if i >= len(msgs) {96 return nil97 }98 return msgs[i]99}100var search = flag.String("search", "", "search query")101func main() {102 flag.BoolVar(&imap.Debug, "imapdebug", false, "imap debugging trace")103 flag.Parse()104 acct = google.Acct(*acctName)105 if args := flag.Args(); len(args) > 0 {106 for i := range args {107 args[i] = "-to=" + args[i]108 }109 cmd := exec.Command("gmailsend", append([]string{"-a", acct.Email, "-i"}, args...)...)110 cmd.Stdin = os.Stdin111 cmd.Stdout = os.Stdout112 cmd.Stderr = os.Stderr113 if err := cmd.Run(); err != nil {114 fmt.Fprintf(os.Stderr, "!%s\n", err)115 os.Exit(1)116 }117 return118 }119 c, err := imap.NewClient(imap.TLS, "imap.gmail.com", acct.Email, acct.Password, "")120 if err != nil {121 log.Fatal(err)122 }123 isGmail = c.IsGmail()124 threaded = isGmail125 if *search != "" {126 b, err := c.GmailSearch(*search)127 if err != nil {128 log.Fatal(err)129 }130 inbox = b131 } else {132 inbox = c.Inbox()133 if err := inbox.Check(); err != nil {134 log.Fatal(err)135 }136 }137 msgs = inbox.Msgs()138 maxfrom = 12139 for i, m := range msgs {140 msgNum[m] = i141 if n := len(from(m.Hdr)); n > maxfrom {142 maxfrom = n143 }144 }145 if maxfrom > 20 {146 maxfrom = 20147 }148 subjlen = 80 - maxfrom149 rethread()150 interrupts := make(chan os.Signal, 1)151 signal.Notify(interrupts, syscall.SIGINT)152 go func() {153 for _ = range interrupts {154 fmt.Fprintf(os.Stderr, "!interrupt\n")155 interrupted = true156 }157 }()158 for {159 if dot != nil {160 fmt.Fprintf(bout, "%d", msgNum[dot.Msg]+1)161 if dot != &dot.Msg.Root {162 fmt.Fprintf(bout, ".%s", dot.ID)163 }164 }165 fmt.Fprintf(bout, ": ")166 bout.Flush()167 line, err := bin.ReadString('\n')168 if err != nil {169 break170 }171 cmd, err := parsecmd(line)172 if err != nil {173 fmt.Fprintf(bout, "!%s\n", err)174 continue175 }176 if cmd.Targ != nil || cmd.Targs == nil && cmd.A2 == 0 {177 x := cmd.F(cmd, cmd.Targ)178 if x != nil {179 dot = x180 }181 } else {182 targs := cmd.Targs183 if targs == nil {184 delta := +1185 if cmd.A1 > cmd.A2 {186 delta = -1187 }188 for i := cmd.A1; i <= cmd.A2; i += delta {189 if i < 1 || i > len(msgs) {190 continue191 }192 targs = append(targs, msgs[i-1])193 }194 }195 if cmd.Thread {196 if !isGmail {197 fmt.Fprintf(bout, "!need gmail for threaded command\n")198 continue199 }200 byThread := make(map[uint64][]*imap.Msg)201 for _, m := range msgs {202 t := m.GmailThread203 byThread[t] = append(byThread[t], m)204 }205 for _, m := range targs {206 t := m.GmailThread207 if byThread[t] != nil {208 if cmd.TF != nil {209 if x := cmd.TF(cmd, byThread[t]); x != nil {210 dot = x211 }212 } else {213 for _, mm := range byThread[t] {214 x := cmd.F(cmd, &mm.Root)215 if x != nil {216 dot = x217 }218 }219 }220 }221 delete(byThread, t)222 }223 continue224 }225 for _, m := range targs {226 if cmd.Delete {227 dcmd(cmd, &m.Root)228 if cmd.Name == "p" {229 // dp is a special case: it advances to the next message before the p.230 next := nextMsg(m)231 if next == nil {232 fmt.Fprintf(bout, "!address\n")233 dot = &m.Root234 break235 }236 m = next237 }238 }239 x := cmd.F(cmd, &m.Root)240 if x != nil {241 dot = x242 }243 // TODO: Break loop on interrupt.244 }245 }246 }247 qcmd(nil, nil)248}249func parsecmd(line string) (cmd *Cmd, err error) {250 cmd = &Cmd{}251 line = strings.TrimSpace(line)252 if line == "" {253 // Empty command is a special case: advance and print.254 cmd.F = pcmd255 if dot == nil {256 cmd.A1 = 1257 cmd.A2 = 1258 } else {259 n := msgNum[dot.Msg] + 2260 if n > len(msgs) {261 return nil, fmt.Errorf("out of messages")262 }263 cmd.A1 = n264 cmd.A2 = n265 }266 return cmd, nil267 }268 // Global search?269 if line[0] == 'g' {270 line = line[1:]271 if line == "" || line[0] != '/' {272 // No search string means all messages.273 cmd.A1 = 1274 cmd.A2 = len(msgs)275 } else if line[0] == '/' {276 re, rest, err := parsere(line)277 if err != nil {278 return nil, err279 }280 line = rest281 // Find all messages matching this search string.282 var targ []*imap.Msg283 for _, m := range msgs {284 if re.MatchString(header(m)) {285 targ = append(targ, m)286 }287 }288 if len(targ) == 0 {289 return nil, fmt.Errorf("no matches")290 }291 cmd.Targs = targ292 }293 } else {294 // Parse an address.295 a1, targ, rest, err := parseaddr(line, 1)296 if err != nil {297 return nil, err298 }299 if targ != nil {300 cmd.Targ = targ301 line = rest302 } else {303 if a1 < 1 || a1 > len(msgs) {304 return nil, fmt.Errorf("message number %d out of range", a1)305 }306 cmd.A1 = a1307 cmd.A2 = a1308 a2 := a1309 if rest != "" && rest[0] == ',' {310 // This is an address range.311 a2, targ, rest, err = parseaddr(rest[1:], len(msgs))312 if err != nil {313 return nil, err314 }315 if a2 < 1 || a2 > len(msgs) {316 return nil, fmt.Errorf("message number %d out of range", a2)317 }318 cmd.A2 = a2319 } else if rest == line {320 // There was no address.321 if dot == nil {322 cmd.A1 = 1323 cmd.A2 = 0324 } else {325 if dot != nil {326 if dot == &dot.Msg.Root {327 // If dot is a plain msg, use a range so that dp works.328 cmd.A1 = msgNum[dot.Msg] + 1329 cmd.A2 = cmd.A1330 } else {331 cmd.Targ = dot332 }333 }334 }335 }336 line = rest337 }338 }339 cmd.Line = strings.TrimSpace(line)340 // Insert space after ! or | for tokenization.341 switch {342 case strings.HasPrefix(cmd.Line, "||"):343 cmd.Line = cmd.Line[:2] + " " + cmd.Line[2:]344 case strings.HasPrefix(cmd.Line, "!"), strings.HasPrefix(cmd.Line, "|"):345 cmd.Line = cmd.Line[:1] + " " + cmd.Line[1:]346 }347 av := strings.Fields(cmd.Line)348 cmd.Args = av349 if len(av) == 0 || av[0] == "" {350 // Default is to print.351 cmd.F = pcmd352 return cmd, nil353 }354 name := av[0]355 cmd.ArgLine = strings.TrimSpace(cmd.Line[len(av[0]):])356 // Hack to allow t prefix on all commands.357 if len(name) >= 2 && name[0] == 't' {358 cmd.Thread = true359 name = name[1:]360 }361 // Hack to allow d prefix on all commands.362 if len(name) >= 2 && name[0] == 'd' {363 cmd.Delete = true364 name = name[1:]365 }366 cmd.Name = name367 // Search command table.368 for _, ct := range cmdtab {369 if ct.Name == name {370 if ct.Args == 0 && len(av) > 1 {371 return nil, fmt.Errorf("%s doesn't take an argument", name)372 }373 cmd.F = ct.F374 cmd.TF = ct.TF375 if name == "m" {376 // mute applies to all thread no matter what377 cmd.Thread = true378 }379 return cmd, nil380 }381 }382 return nil, fmt.Errorf("unknown command %s", name)383}384func parseaddr(addr string, deflt int) (n int, targ *imap.MsgPart, rest string, err error) {385 dot := dot386 n = deflt387 for {388 old := addr389 n, targ, rest, err = parseaddr1(addr, n, dot)390 if targ != nil || rest == old || err != nil {391 break392 }393 if n < 1 || n > len(msgs) {394 return 0, nil, "", fmt.Errorf("message number %d out of range", n)395 }396 dot = &msgs[n-1].Root397 addr = rest398 }399 return400}401func parseaddr1(addr string, deflt int, dot *imap.MsgPart) (n int, targ *imap.MsgPart, rest string, err error) {402 base := 0403 if dot != nil {404 base = msgNum[dot.Msg] + 1405 }406 if addr == "" {407 return deflt, nil, addr, nil408 }409 var i int410 sign := 0411 switch c := addr[0]; c {412 case '+':413 sign = +1414 addr = addr[1:]415 case '-':416 sign = -1417 addr = addr[1:]418 case '.':419 if base == 0 {420 return 0, nil, "", fmt.Errorf("no message selected")421 }422 n = base423 i = 1424 goto HaveNumber425 case '$':426 if len(msgs) == 0 {427 return 0, nil, "", fmt.Errorf("no messages")428 }429 n = len(msgs)430 i = 1431 goto HaveNumber432 case '/', '?':433 var re *regexp.Regexp434 re, addr, err = parsere(addr)435 if err != nil {436 return437 }438 var delta int439 if c == '/' {440 delta = +1441 } else {442 delta = -1443 }444 for j := base + delta; 1 <= j && j <= len(msgs); j += delta {445 if re.MatchString(header(msgs[j-1])) {446 n = j447 i = 0 // already cut addr448 goto HaveNumber449 }450 }451 err = fmt.Errorf("search")452 return453 // TODO case '%'454 }455 for i = 0; i < len(addr) && '0' <= addr[i] && addr[i] <= '9'; i++ {456 n = 10*n + int(addr[i]) - '0'457 }458 if sign != 0 {459 if n == 0 {460 n = 1461 }462 n = base + n*sign463 goto HaveNumber464 }465 if i == 0 {466 return deflt, nil, addr, nil467 }468HaveNumber:469 rest = addr[i:]470 if i < len(addr) && addr[i] == '.' {471 if n < 1 || n > len(msgs) {472 err = fmt.Errorf("message number %d out of range", n)473 return474 }475 targ = &msgs[n-1].Root476 for i < len(addr) && addr[i] == '.' {477 i++478 var j int479 n = 0480 for j = i; j < len(addr) && '0' <= addr[j] && addr[j] <= '9'; j++ {481 n = 10*n + int(addr[j]) - '0'482 }483 if j == i {484 err = fmt.Errorf("malformed message number %s", addr[:j])485 return486 }487 if n < 1 || n > len(targ.Child) {488 err = fmt.Errorf("message number %s out of range", addr[:j])489 return490 }491 targ = targ.Child[n-1]492 i = j493 }494 n = 0495 rest = addr[i:]496 return497 }498 return499}500func parsere(addr string) (re *regexp.Regexp, rest string, err error) {501 prog, rest, err := parseprog(addr)502 if err != nil {503 return504 }505 re, err = regexp.Compile(prog)506 return507}508var lastProg string509func parseprog(addr string) (prog string, rest string, err error) {510 if len(addr) == 1 {511 if lastProg != "" {512 return lastProg, "", nil513 }514 err = fmt.Errorf("no search")515 return516 }517 i := strings.Index(addr[1:], addr[:1])518 if i < 0 {519 prog = addr[1:]520 rest = ""521 } else {522 i += 1 // adjust for slice in IndexByte arg523 prog, rest = addr[1:i], addr[i+1:]524 }525 lastProg = prog526 return527}528func bcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {529 var m *imap.Msg530 if dot == nil {531 if len(msgs) == 0 {532 return nil533 }534 m = msgs[0]535 } else {536 m = dot.Msg537 }538 for i := 0; i < 10; i++ {539 hcmd(c, &m.Root)540 next := nextMsg(m)541 if next == nil {542 break543 }544 m = next545 }546 return &m.Root547}548func dcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {549 if dot == nil {550 fmt.Fprintf(bout, "!address\n")551 return nil552 }553 deleted[dot.Msg] = true554 return &dot.Msg.Root555}556func tdcmd(c *Cmd, msgs []*imap.Msg) *imap.MsgPart {557 if len(msgs) == 0 {558 fmt.Fprintf(bout, "!address\n")559 return nil560 }561 for _, m := range msgs {562 deleted[m] = true563 }564 return &msgs[len(msgs)-1].Root565}566func ucmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {567 if dot == nil {568 fmt.Fprintf(bout, "!address\n")569 return nil570 }571 delete(deleted, dot.Msg)572 return &dot.Msg.Root573}574func eqcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {575 if dot == nil {576 fmt.Fprintf(bout, "0")577 } else {578 fmt.Fprintf(bout, "%d", msgNum[dot.Msg]+1)579 if dot != &dot.Msg.Root {580 fmt.Fprintf(bout, ".%s", dot.ID)581 }582 }583 fmt.Fprintf(bout, "\n")584 return nil585}586func from(h *imap.MsgHdr) string {587 if len(h.From) < 1 {588 return "?"589 }590 if name := h.From[0].Name; name != "" {591 return name592 }593 return h.From[0].Email594}595func header(m *imap.Msg) string {596 var t string597 if time.Now().Sub(m.Date) < 365*24*time.Hour {598 t = m.Date.Format("01/02 15:04")599 } else {600 t = m.Date.Format("01/02 2006 ")601 }602 ch := ' '603 if len(m.Root.Child) > 1 || len(m.Root.Child) == 1 && len(m.Root.Child[0].Child) > 0 {604 ch = 'H'605 }606 del := ' '607 if deleted[m] {608 del = 'd'609 }610 return fmt.Sprintf("%-3d %c%c %s %-*.*s %.*s",611 msgNum[m]+1, ch, del, t,612 maxfrom, maxfrom, from(m.Hdr),613 subjlen, m.Hdr.Subject)614}615func hcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {616 if dot != nil {617 fmt.Fprintf(bout, "%s\n", header(dot.Msg))618 }619 return nil620}621func helpcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {622 fmt.Fprint(bout, "Commands are of the form [<range>] <command> [args]\n")623 fmt.Fprint(bout, "<range> := <addr> | <addr>','<addr>| 'g'<search>\n")624 fmt.Fprint(bout, "<addr> := '.' | '$' | '^' | <number> | <search> | <addr>'+'<addr> | <addr>'-'<addr>\n")625 fmt.Fprint(bout, "<search> := '/'<gmail search>'/' | '?'<gmail search>'?'\n")626 fmt.Fprint(bout, "<command> :=\n")627 for _, ct := range cmdtab {628 fmt.Fprintf(bout, "%s\n", ct.Help)629 }630 return dot631}632func mimecmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {633 if dot != nil {634 mimeH(fmt.Sprint(msgNum[dot.Msg]+1), dot)635 }636 return nil637}638func mimeH(id string, p *imap.MsgPart) {639 if p.ID != "" {640 id = id + "." + p.ID641 }642 fmt.Fprintf(bout, "%s %s %s %#q %d\n", id, p.Type, p.Encoding+"/"+p.Charset, p.Name, p.Bytes)643 for _, child := range p.Child {644 mimeH(id, child)645 }646}647func icmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {648 sync(false)649 return nil650}651func ycmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {652 sync(true)653 return nil654}655func tpluscmd(c *Cmd, msgs []*imap.Msg) *imap.MsgPart {656 if len(msgs) == 0 {657 return nil658 }659 m := nextMsg(msgs[len(msgs)-1])660 if m == nil {661 fmt.Fprintf(bout, "!no more messages\n")662 return nil663 }664 return pcmd(c, &m.Root)665}666func pluscmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {667 if dot == nil {668 return nil669 }670 m := nextMsg(dot.Msg)671 if m == nil {672 fmt.Fprintf(bout, "!no more messages\n")673 return nil674 }675 return pcmd(c, &m.Root)676}677func addrlist(x []imap.Addr) string {678 var b bytes.Buffer679 for i, a := range x {680 if i > 0 {681 b.WriteString(", ")682 }683 b.WriteString(a.String())684 }685 return b.String()686}687func wpcmd(w io.Writer, c *Cmd, dot *imap.MsgPart) *imap.MsgPart {688 if dot == nil {689 return nil690 }691 if dot == &dot.Msg.Root {692 h := dot.Msg.Hdr693 if len(h.From) > 0 {694 fmt.Fprintf(w, "From: %s\n", addrlist(h.From))695 }696 fmt.Fprintf(w, "Date: %s\n", dot.Msg.Date)697 if len(h.From) > 0 {698 fmt.Fprintf(w, "To: %s\n", addrlist(h.To))699 }700 if len(h.CC) > 0 {701 fmt.Fprintf(w, "CC: %s\n", addrlist(h.CC))702 }703 if len(h.BCC) > 0 {704 fmt.Fprintf(w, "BCC: %s\n", addrlist(h.BCC))705 }706 if len(h.Subject) > 0 {707 fmt.Fprintf(w, "Subject: %s\n", h.Subject)708 }709 fmt.Fprintf(w, "\n")710 }711 printMIME(w, dot, true)712 fmt.Fprintf(w, "\n")713 return dot714}715func pcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {716 defer bout.Flush()717 return wpcmd(bout, c, dot)718}719func pipecmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {720 args := c.Args[1:]721 if len(args) == 0 {722 fmt.Fprintf(bout, "!no command\n")723 return dot724 }725 bout.Flush()726 cmd := exec.Command(args[0], args[1:]...)727 w, err := cmd.StdinPipe()728 if err != nil {729 fmt.Fprintf(bout, "!%s\n", err)730 return dot731 }732 cmd.Stdout = os.Stdout733 cmd.Stderr = os.Stderr734 if err := cmd.Start(); err != nil {735 fmt.Fprintf(bout, "!%s\n", err)736 return dot737 }738 wpcmd(w, c, dot)739 w.Close()740 if err := cmd.Wait(); err != nil {741 fmt.Fprintf(bout, "!%s\n", err)742 }743 return dot744}745func bangcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {746 args := c.Args[1:]747 if len(args) == 0 {748 fmt.Fprintf(bout, "!no command\n")749 return dot750 }751 bout.Flush()752 cmd := exec.Command(args[0], args[1:]...)753 cmd.Stdin = os.Stdin754 cmd.Stdout = os.Stdout755 cmd.Stderr = os.Stderr756 if err := cmd.Run(); err != nil {757 fmt.Fprintf(bout, "!%s\n", err)758 }759 return nil760}761func unixfrom(h *imap.MsgHdr) string {762 if len(h.From) == 0 {763 return ""764 }765 return h.From[0].Email766}767func unixtime(m *imap.Msg) string {768 return dot.Msg.Date.Format("Mon Jan _2 15:04:05 MST 2006")769}770func Pcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {771 if dot == nil {772 return nil773 }774 if dot == &dot.Msg.Root {775 fmt.Fprintf(bout, "From %s %s\n",776 unixfrom(dot.Msg.Hdr),777 unixtime(dot.Msg))778 }779 bout.Write(dot.Raw())780 return dot781}782func printMIME(w io.Writer, p *imap.MsgPart, top bool) {783 switch {784 case top && strings.HasPrefix(p.Type, "text/"):785 text := p.ShortText()786 if p.Type == "text/html" {787 cmd := exec.Command("htmlfmt")788 cmd.Stdin = bytes.NewBuffer(text)789 if w == bout {790 bout.Flush()791 cmd.Stdout = os.Stdout792 } else {793 cmd.Stdout = w794 }795 if err := cmd.Run(); err != nil {796 fmt.Fprintf(w, "%d.%s !%s\n", msgNum[p.Msg]+1, p.ID, err)797 }798 return799 }800 w.Write(text)801 case p.Type == "text/plain":802 if top {803 panic("printMIME loop")804 }805 printMIME(w, p, true)806 case p.Type == "multipart/alternative":807 for _, pp := range p.Child {808 if pp.Type == "text/plain" {809 printMIME(w, pp, false)810 return811 }812 }813 if len(p.Child) > 0 {814 printMIME(w, p.Child[0], false)815 }816 case strings.HasPrefix(p.Type, "multipart/"):817 for _, pp := range p.Child {818 printMIME(w, pp, false)819 }820 default:821 fmt.Fprintf(w, "%d.%s !%s %s %s\n", msgNum[p.Msg]+1, p.ID, p.Type, p.Desc, p.Name)822 }823}824func qcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {825 flushDeleted()826 xcmd(c, dot)827 panic("not reached")828}829type quoter struct {830 bol bool831 w io.Writer832}833func (q *quoter) Write(b []byte) (n int, err error) {834 n = len(b)835 err = nil836 for len(b) > 0 {837 if q.bol {838 q.w.Write([]byte("> "))839 q.bol = false840 }841 i := bytes.IndexByte(b, '\n')842 if i < 0 {843 i = len(b)844 } else {845 q.bol = true846 i++847 }848 q.w.Write(b[:i])849 b = b[i:]850 }851 return852}853func quotecmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {854 if dot == nil {855 return nil856 }857 m := dot.Msg858 if len(m.Hdr.From) != 0 {859 a := m.Hdr.From[0]860 name := a.Name861 if name == "" {862 name = a.Email863 }864 date := m.Date.Format("Jan 2, 2006 at 15:04")865 fmt.Fprintf(bout, "On %s, %s wrote:\n", date, name)866 }867 printMIME(&quoter{true, bout}, dot, true)868 return dot869}870func addre(s string) string {871 if len(s) < 4 || !strings.EqualFold(s[:4], "re: ") {872 return "Re: " + s873 }874 return s875}876func rcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {877 if dot == nil || dot.Msg.Hdr == nil {878 fmt.Fprintf(bout, "!nothing to reply to\n")879 return nil880 }881 h := dot.Msg.Hdr882 replyTo := h.ReplyTo883 have := make(map[string]bool)884 if len(replyTo) == 0 {885 replyTo = h.From886 }887 if c.Name[0] == 'a' {888 for _, a := range replyTo {889 have[a.Email] = true890 }891 for _, a := range append(append(append([]imap.Addr(nil), h.From...), h.To...), h.CC...) {892 if !have[a.Email] {893 have[a.Email] = true894 replyTo = append(replyTo, a)895 }896 }897 }898 if len(replyTo) == 0 {899 fmt.Fprintf(bout, "!no one to reply to\n")900 return dot901 }902 args := []string{"-a", acct.Email, "-s", addre(h.Subject), "-in-reply-to", h.MessageID}903 fmt.Fprintf(bout, "replying to:")904 for _, a := range replyTo {905 fmt.Fprintf(bout, " %s", a.Email)906 args = append(args, "-to", a.String())907 }908 for _, arg := range c.Args[1:] {909 fmt.Fprintf(bout, " %s", arg)910 args = append(args, "-to", arg)911 }912 fmt.Fprintf(bout, "\n")913 bout.Flush()914 cmd := exec.Command("gmailsend", args...)915 cmd.Stdin = os.Stdin916 cmd.Stdout = os.Stdout917 cmd.Stderr = os.Stderr918 err := cmd.Run()919 if err != nil {920 fmt.Fprintf(bout, "!%s\n", err)921 }922 return dot923}924func fcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {925 if dot == nil {926 fmt.Fprintf(bout, "!nothing to forward\n")927 return nil928 }929 return fwd(c, dot, nil)930}931func tfcmd(c *Cmd, msgs []*imap.Msg) *imap.MsgPart {932 if len(msgs) == 0 {933 fmt.Fprintf(bout, "!nothing to forward\n")934 return nil935 }936 return fwd(c, &msgs[len(msgs)-1].Root, msgs)937}938func fwd(c *Cmd, dot *imap.MsgPart, msgs []*imap.Msg) *imap.MsgPart {939 addrs := c.Args[1:]940 if len(addrs) == 0 {941 fmt.Fprintf(bout, "!f command requires address to forward to\n")942 return dot943 }944 h := dot.Msg.Hdr945 args := []string{"-a", acct.Email, "-s", "Fwd: " + h.Subject, "-append", "/dev/fd/3"}946 fmt.Fprintf(bout, "forwarding to:")947 for _, arg := range addrs {948 fmt.Fprintf(bout, " %s", arg)949 args = append(args, "-to", arg)950 }951 fmt.Fprintf(bout, "\n")952 bout.Flush()953 cmd := exec.Command("gmailsend", args...)954 r, w, err := os.Pipe()955 if err != nil {956 fmt.Fprintf(bout, "!%s\n", err)957 return dot958 }959 cmd.Stdin = os.Stdin960 cmd.Stdout = os.Stdout961 cmd.Stderr = os.Stderr962 cmd.ExtraFiles = []*os.File{r}963 if err := cmd.Start(); err != nil {964 r.Close()965 fmt.Fprintf(bout, "!%s\n", err)966 return dot967 }968 r.Close()969 what := "message"970 if len(msgs) > 1 {971 what = "conversation"972 }973 fmt.Fprintf(w, "\n\n--- Forwarded %s ---\n", what)974 if msgs == nil {975 wpcmd(w, c, dot)976 } else {977 for _, m := range msgs {978 wpcmd(w, c, &m.Root)979 fmt.Fprintf(w, "\n\n")980 }981 }982 w.Close()983 if err := cmd.Wait(); err != nil {984 fmt.Fprintf(bout, "!%s\n", err)985 }986 return dot987}988func rethread() {989 if !threaded {990 sort.Sort(byUIDRev(msgs))991 } else {992 byThread := make(map[uint64][]*imap.Msg)993 for _, m := range msgs {994 t := m.GmailThread995 byThread[t] = append(byThread[t], m)996 }997 var threadList [][]*imap.Msg998 for _, t := range byThread {999 sort.Sort(byUID(t))1000 threadList = append(threadList, t)1001 }1002 sort.Sort(byUIDList(threadList))1003 msgs = msgs[:0]1004 for _, t := range threadList {1005 msgs = append(msgs, t...)1006 }1007 }1008 for i, m := range msgs {1009 msgNum[m] = i1010 }1011}1012type byUID []*imap.Msg1013func (l byUID) Less(i, j int) bool { return l[i].UID < l[j].UID }1014func (l byUID) Len() int { return len(l) }1015func (l byUID) Swap(i, j int) { l[i], l[j] = l[j], l[i] }1016type byUIDRev []*imap.Msg1017func (l byUIDRev) Less(i, j int) bool { return l[i].UID > l[j].UID }1018func (l byUIDRev) Len() int { return len(l) }1019func (l byUIDRev) Swap(i, j int) { l[i], l[j] = l[j], l[i] }1020type byUIDList [][]*imap.Msg1021func (l byUIDList) Less(i, j int) bool { return l[i][len(l[i])-1].UID > l[j][len(l[j])-1].UID }1022func (l byUIDList) Len() int { return len(l) }1023func (l byUIDList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }1024func subj(m *imap.Msg) string {1025 s := m.Hdr.Subject1026 for strings.HasPrefix(s, "Re: ") || strings.HasPrefix(s, "RE: ") {1027 s = s[4:]1028 }1029 return s1030}1031func mcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {1032 c.ArgLine = "Muted"1033 scmd(c, dot)1034 return dcmd(c, dot)1035}1036func tmcmd(c *Cmd, msgs []*imap.Msg) *imap.MsgPart {1037 c.ArgLine = "Muted"1038 tscmd(c, msgs)1039 return tdcmd(c, msgs)1040}1041func scmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {1042 if dot == nil {1043 return nil1044 }1045 return tscmd(c, []*imap.Msg{dot.Msg})1046}1047func tscmd(c *Cmd, msgs []*imap.Msg) *imap.MsgPart {1048 if len(msgs) == 0 {1049 return nil1050 }1051 arg := c.ArgLine1052 dot := &msgs[len(msgs)-1].Root1053 if arg == "" {1054 fmt.Fprintf(bout, "!s needs mailbox (label) name as argument\n")1055 return dot1056 }1057 if strings.EqualFold(arg, "Muted") {1058 if err := dot.Msg.Box.Mute(msgs); err != nil {1059 fmt.Fprintf(bout, "!mute: %s\n", err)1060 }1061 } else {1062 dst := dot.Msg.Box.Client.Box(arg)1063 if dst == nil {1064 fmt.Fprintf(bout, "!unknown mailbox %#q", arg)1065 return dot1066 }1067 if err := dst.Copy(msgs); err != nil {1068 fmt.Fprintf(bout, "!s %#q: %s\n", arg, err)1069 }1070 }1071 return dot1072}1073func Wcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {1074 if dot == nil {1075 return nil1076 }1077 if !isGmail {1078 fmt.Fprintf(bout, "!cmd W requires gmail\n")1079 return dot1080 }1081 url := fmt.Sprintf("https://mail.google.com/mail/b/%s/?shva=1#inbox/%x", acct.Email, dot.Msg.GmailThread)1082 if err := exec.Command("open", url).Run(); err != nil {1083 fmt.Fprintf(bout, "!%s\n", err)1084 }1085 return dot1086}1087func xcmd(c *Cmd, dot *imap.MsgPart) *imap.MsgPart {1088 // TODO: remove saved attachments?1089 os.Exit(0)1090 panic("not reached")1091}1092func flushDeleted() {1093 var toDelete []*imap.Msg1094 for m := range deleted {1095 toDelete = append(toDelete, m)1096 }1097 if len(toDelete) == 0 {1098 return1099 }1100 fmt.Fprintf(os.Stderr, "!deleting %d\n", len(toDelete))1101 err := inbox.Delete(toDelete)1102 if err != nil {1103 fmt.Fprintf(os.Stderr, "!deleting: %s\n", err)1104 }1105}1106func loadNew() {1107 if err := inbox.Check(); err != nil {1108 fmt.Fprintf(os.Stderr, "!inbox: %s\n", err)1109 }1110 old := make(map[*imap.Msg]bool)1111 for _, m := range msgs {1112 old[m] = true1113 }1114 nnew := 01115 new := inbox.Msgs()1116 for _, m := range new {1117 if old[m] {1118 delete(old, m)1119 } else {1120 msgs = append(msgs, m)1121 nnew++1122 }1123 }1124 if nnew > 0 {1125 fmt.Fprintf(os.Stderr, "!%d new messages\n", nnew)1126 }1127 for m := range old {1128 // Deleted1129 m.Flags |= imap.FlagDeleted1130 delete(deleted, m)1131 }1132}1133func sync(delete bool) {1134 if delete {1135 flushDeleted()1136 }1137 loadNew()1138 if delete {1139 w := 01140 for _, m := range msgs {1141 if !m.Deleted() {1142 msgs[w] = m1143 w++1144 }1145 }1146 msgs = msgs[:w]1147 }1148 rethread()1149}...

Full Screen

Full Screen

imap.go

Source:imap.go Github

copy

Full Screen

...19 TLS bool `json:"tls"`20 IgnoreCertErrors bool `json:"ignore_cert_errors"`21 Folder string `json:"folder"`22 RestrictDomain string `json:"restrict_domain"`23 DeleteReportedCampaignEmail bool `json:"delete_reported_campaign_email"`24 LastLogin time.Time `json:"last_login,omitempty"`25 ModifiedDate time.Time `json:"modified_date"`26 IMAPFreq uint32 `json:"imap_freq,string,omitempty"`27}28// ErrIMAPHostNotSpecified is thrown when there is no Host specified29// in the IMAP configuration30var ErrIMAPHostNotSpecified = errors.New("No IMAP Host specified")31// ErrIMAPPortNotSpecified is thrown when there is no Port specified32// in the IMAP configuration33var ErrIMAPPortNotSpecified = errors.New("No IMAP Port specified")34// ErrInvalidIMAPHost indicates that the IMAP server string is invalid35var ErrInvalidIMAPHost = errors.New("Invalid IMAP server address")36// ErrInvalidIMAPPort indicates that the IMAP Port is invalid37var ErrInvalidIMAPPort = errors.New("Invalid IMAP Port")38// ErrIMAPUsernameNotSpecified is thrown when there is no Username specified39// in the IMAP configuration40var ErrIMAPUsernameNotSpecified = errors.New("No Username specified")41// ErrIMAPPasswordNotSpecified is thrown when there is no Password specified42// in the IMAP configuration43var ErrIMAPPasswordNotSpecified = errors.New("No Password specified")44// ErrInvalidIMAPFreq is thrown when the frequency for polling the45// IMAP server is invalid46var ErrInvalidIMAPFreq = errors.New("Invalid polling frequency")47// TableName specifies the database tablename for Gorm to use48func (im IMAP) TableName() string {49 return "imap"50}51// Validate ensures that IMAP configs/connections are valid52func (im *IMAP) Validate() error {53 switch {54 case im.Host == "":55 return ErrIMAPHostNotSpecified56 case im.Port == 0:57 return ErrIMAPPortNotSpecified58 case im.Username == "":59 return ErrIMAPUsernameNotSpecified60 case im.Password == "":61 return ErrIMAPPasswordNotSpecified62 }63 // Set the default value for Folder64 if im.Folder == "" {65 im.Folder = DefaultIMAPFolder66 }67 // Make sure im.Host is an IP or hostname. NB will fail if unable to resolve the hostname.68 ip := net.ParseIP(im.Host)69 _, err := net.LookupHost(im.Host)70 if ip == nil && err != nil {71 return ErrInvalidIMAPHost72 }73 // Make sure 1 >= port <= 6553574 if im.Port < 1 || im.Port > 65535 {75 return ErrInvalidIMAPPort76 }77 // Make sure the polling frequency is between every 30 seconds and every year78 // If not set it to the default79 if im.IMAPFreq < 30 || im.IMAPFreq > 31540000 {80 im.IMAPFreq = DefaultIMAPFreq81 }82 return nil83}84// GetIMAP returns the IMAP server owned by the given user.85func GetIMAP(uid int64) ([]IMAP, error) {86 im := []IMAP{}87 count := 088 err := db.Where("user_id=?", uid).Find(&im).Count(&count).Error89 if err != nil {90 log.Error(err)91 return im, err92 }93 return im, nil94}95// PostIMAP updates IMAP settings for a user in the database.96func PostIMAP(im *IMAP, uid int64) error {97 err := im.Validate()98 if err != nil {99 log.Error(err)100 return err101 }102 // Delete old entry. TODO: Save settings and if fails to Save below replace with original103 err = DeleteIMAP(uid)104 if err != nil {105 log.Error(err)106 return err107 }108 // Insert new settings into the DB109 err = db.Save(im).Error110 if err != nil {111 log.Error("Unable to save to database: ", err.Error())112 }113 return err114}115// DeleteIMAP deletes the existing IMAP in the database.116func DeleteIMAP(uid int64) error {117 err := db.Where("user_id=?", uid).Delete(&IMAP{}).Error118 if err != nil {119 log.Error(err)120 }121 return err122}123func SuccessfulLogin(im *IMAP) error {124 err := db.Model(&im).Where("user_id = ?", im.UserId).Update("last_login", time.Now().UTC()).Error125 if err != nil {126 log.Error("Unable to update database: ", err.Error())127 }128 return err129}...

Full Screen

Full Screen

test.go

Source:test.go Github

copy

Full Screen

...54 log.Printf("[INFO] imap: found %v messages, %v unseen", mbox.Messages, mbox.Unseen)55 // set for all messages56 seqSet := new(imap.SeqSet)57 seqSet.AddRange(from, to)58 // set for delete messages59 deleteSet := new(imap.SeqSet)60 // get the whole message body61 section := &imap.BodySectionName{}62 items := []imap.FetchItem{section.FetchItem(), imap.FetchRFC822, imap.FetchEnvelope, imap.FetchBody, imap.FetchFlags, imap.FetchInternalDate}63 messages := make(chan *imap.Message, 1)64 done := make(chan error, 1)65 go func() {66 done <- c.Fetch(seqSet, items, messages)67 }()68 downloadCount := 069 for msg := range messages {70 if msg == nil {71 return fmt.Errorf("server didn't return message")72 }73 br := msg.GetBody(section)74 if br == nil {75 return fmt.Errorf("server didn't return message body")76 }77 fmt.Println(msg.Envelope.From)78 fmt.Println("SUBJECT ", msg.Envelope.Subject)79 fmt.Println("FROM ", msg.Envelope.From)80 fmt.Println("TO ", msg.Envelope.Date)81 body := make([]byte, 10000)82 br.Read(body)83 fmt.Println("BODY")84 fmt.Println(string(body))85 // create a new mail reader86 mr, err := mail.CreateReader(br)87 if err != nil {88 return err89 }90 // process each message's part91 isSuccess := false92 for {93 p, err := mr.NextPart()94 if err == io.EOF {95 break96 } else if err != nil {97 log.Printf("[ERROR] imap: can't read next part: %v, skip", err)98 isSuccess = false99 break100 }101 fmt.Println("SUB ", p.Header.Get("Subject"))102 switch h := p.Header.(type) {103 case *mail.Header:104 b, _ := ioutil.ReadAll(p.Body)105 log.Println("BB ", string(b))106 case *mail.AttachmentHeader:107 // this is an attachment108 filename, err := h.Filename()109 if err != nil {110 log.Printf("[ERROR] imap: %v, skip", err)111 continue112 }113 log.Printf("[INFO] imap: found attachment: %v", filename)114 outFile := filepath.Join(".", filename)115 log.Printf("[INFO] imap: save attachment to: %v", outFile)116 f, err := os.Create(outFile)117 if err != nil {118 log.Printf("[ERROR] imap: %v, skip", err)119 continue120 }121 _, err = io.Copy(f, p.Body)122 if err != nil {123 log.Printf("[ERROR] imap: %v, skip", err)124 continue125 }126 f.Close()127 }128 }129 if isSuccess {130 log.Printf("[DEBUG] imap: add SeqNum %v to delete set", msg.SeqNum)131 deleteSet.AddNum(msg.SeqNum)132 }133 downloadCount++134 fmt.Println()135 fmt.Println()136 fmt.Println()137 }138 log.Printf("[DEBUG] imap: %v attachments downloaded", downloadCount)139 if err := <-done; err != nil {140 return err141 }142 // if cfg.Input.IMAP.Delete {143 // log.Printf("[DEBUG] imap: delete emails after fetch")144 // // first, mark the messages as deleted145 // delItems := imap.FormatFlagsOp(imap.AddFlags, false)146 // delFlags := []interface{}{imap.DeletedFlag}147 // err := c.Store(deleteSet, delItems, delFlags, nil)148 // if err != nil {149 // return err150 // }151 // // then delete it152 // if err := c.Expunge(nil); err != nil {153 // return err154 // }155 // }156 return nil157}...

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c, err := client.DialTLS("imap.gmail.com:993", nil)4 if err != nil {5 panic(err)6 }7 defer c.Logout()8 if err := c.Login("

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c, err := client.DialTLS("imap.gmail.com:993", nil)4 if err != nil {5 log.Fatal(err)6 }7 defer c.Logout()8 defer c.Logout()9 if err := c.Login("username", "password"); err != nil {10 log.Fatal(err)11 }12 mbox, err := c.Select("INBOX", true)13 if err != nil {14 log.Fatal(err)15 }16 seqset := new(imap.SeqSet)17 seqset.AddRange(from, to)18 messages := make(chan *imap.Message, 10)19 done := make(chan error, 1)20 go func() {21 done <- c.Fetch(seqset, []imap.FetchItem{imap.FetchEnvelope}, messages)22 }()23 fmt.Println("Last 4 messages:")24 for msg := range messages {25 fmt.Println("* " + msg.Envelope.Subject)26 }27 if err := <-done; err != nil {28 log.Fatal(err)29 }30}

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 m := map[string]int{"Answer": 42}4 fmt.Println("The value:", m["Answer"])5 fmt.Println("The value:", m["Answer"])6 delete(m, "Answer")7 fmt.Println("The value:", m["Answer"])8 fmt.Println("The value:", v, "Present?", ok)9}

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c, err := client.DialTLS("imap.gmail.com:993", nil)4 if err != nil {5 log.Fatal(err)6 }7 log.Println("Connected")8 defer c.Logout()9 if err := c.Login("username", "password"); err != nil {10 log.Fatal(err)11 }12 log.Println("Logged in")13 if _, err := c.Select("INBOX", false); err != nil {14 log.Fatal(err)15 }16 seqset := new(imap.SeqSet)17 seqset.AddNum(1)18 item := imap.FormatFlagsOp(imap.RemoveFlags, true)19 if err := c.Store(seqset, item, []interface{}{imap.DeletedFlag}, nil); err != nil {20 log.Fatal(err)21 }22 if err := c.Expunge(nil); err != nil {23 log.Fatal(err)24 }25 mailboxes := make(chan *imap.MailboxInfo, 10)26 done := make(chan error, 1)27 go func() {28 done <- c.List("", "*", mailboxes)29 }()30 log.Println("Mailboxes:")31 for m := range mailboxes {32 log.Println("* " + m.Name)33 }34 if err := <-done; err != nil {35 log.Fatal(err)36 }37 seqset, err = imap.Wait(c.UIDSearch([]imap.Field{38 imap.NewSearchCriteria().SetUnseen(),39 }))40 if err != nil {41 log.Fatal(err)42 }43 section := &imap.BodySectionName{}44 items := []imap.FetchItem{section.FetchItem()}45 messages := make(chan *imap.Message, 10)46 done = make(chan error, 1)47 go func() {48 done <- c.Fetch(seqset, items, messages)49 }()50 log.Println("Messages:")

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 imap = make(map[string]int)4 fmt.Println("Map before deletion", imap)5 delete(imap, "two")6 fmt.Println("Map after deletion", imap)7}8Go: Delete from Map using delete() method9delete(map, key)10import "fmt"11func main() {12 imap = make(map[string]int)13 fmt.Println("Map before deletion", imap)14 delete(imap, "two")15 fmt.Println("Map after deletion", imap)16}17Go: Delete from Map using delete() method18delete(map, key)19import "fmt"20func main() {21 imap = make(map[string]int)

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 reader := bufio.NewReader(os.Stdin)4 fmt.Println("Enter the string")5 text, _ := reader.ReadString('6 text = strings.TrimSuffix(text, "7 fmt.Println("Enter the character to be deleted")8 char, _ := reader.ReadString('9 char = strings.TrimSuffix(char, "10 fmt.Println("The new string is", strings.Replace(text, char, "", -1))11}

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 imap := imap.NewImap("imap.gmail.com:993", "username", "password")4 imap.Connect()5 imap.Login()6 imap.Select("INBOX")7 imap.Delete(1)8 imap.Logout()9}10import (11func main() {12 imap := imap.NewImap("imap.gmail.com:993", "username", "password")13 imap.Connect()14 imap.Login()15 imap.Select("INBOX")16 imap.Fetch(1)17 imap.Logout()18}19import (20func main() {21 imap := imap.NewImap("imap.gmail.com:993", "username", "password")22 imap.Connect()23 imap.Login()24 imap.Select("INBOX")25 imap.Search("SUBJECT", "test")26 imap.Logout()27}28import (29func main() {30 imap := imap.NewImap("imap.gmail.com:993", "username", "password")31 imap.Connect()32 imap.Login()33 imap.Select("INBOX")34 imap.Store(1, "+FLAGS", "\\Seen")35 imap.Logout()36}37import (38func main() {39 imap := imap.NewImap("imap.gmail.com:993", "username", "password")40 imap.Connect()41 imap.Login()42 imap.Select("INBOX")43 imap.Append("test", "test")44 imap.Logout()45}46import (47func main() {48 imap := imap.NewImap("imap.gmail.com:993", "username", "password")49 imap.Connect()50 imap.Login()51 imap.Select("INBOX")52 imap.Create("test")53 imap.Logout()54}

Full Screen

Full Screen

delete

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c, err := client.DialTLS("imap.gmail.com:993", nil)4 if err != nil {5 log.Fatal(err)6 }7 defer c.Logout()8 if err := c.Login("username", "password"); err != nil {9 log.Fatal(err)10 }11 mailboxes := make(chan *imap.MailboxInfo, 10)12 done := make(chan error, 1)13 go func() {14 done <- c.List("", "*", mailboxes)15 }()16 fmt.Println("Mailboxes:")17 for m := range mailboxes {18 fmt.Println("* " + m.Name)19 }20 if err := <-done; err != nil {21 log.Fatal(err)22 }23 mbox, err := c.Select("INBOX", false)24 if err != nil {25 log.Fatal(err)26 }27 fmt.Println("Flags for INBOX:", mbox.Flags)28 from := uint32(1)29 if mbox.Messages > 4 {30 }31 seqset := new(imap.SeqSet)32 seqset.AddRange(from, to)33 section := &imap.BodySectionName{}34 items := []imap.FetchItem{section.FetchItem()}35 messages := make(chan *imap.Message, 10)36 go func() {37 if err := c.Fetch(seqset, items, messages); err != nil {38 log.Fatal(err)39 }40 }()41 fmt.Println("Last 4 messages:")42 for msg := range messages {43 r := msg.GetBody(section)44 if r == nil {45 log.Fatal("Server didn't returned message body")46 }47 m, err := mail.CreateReader(r)48 if err != nil {49 log.Fatal(err)50 }51 if date, err := header.Date(); err == nil {52 fmt.Println("Date:", date)53 }54 if from, err := header.AddressList("From"); err == nil {55 fmt.Println("From:", from)56 }57 if to, err := header.AddressList("To"); err == nil {58 fmt.Println("To:", to)59 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Venom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful