emersion / go-imap

📥 An IMAP library for clients and servers
MIT License
2.02k stars 288 forks source link

How to clear total email with this "github.com/emersion/go-imap" #619

Open yangyile1990 opened 1 month ago

yangyile1990 commented 1 month ago

can not clear the trash.

I don't know how to do it.

package main

import (
    "fmt"

    "github.com/emersion/go-imap"
    imapID "github.com/emersion/go-imap-id"
    "github.com/emersion/go-imap/client"
    "github.com/yyle88/done"
    softjson "gitlab.yyle.com/golang/uvyyle.git/utils_encoding/utils_encoding_json/utils_neatjson/utils_neatjson_soft"
    "gitlab.yyle.com/golang/uvyyle.git/utils_os/utils_os_args"
)

// 代码参考:https://github.com/richelieu-yang/chimera/blob/288cbdd148693d4962ff7fc544fd3f3cf6ccba89/src/mailKit/imap.go
func main() {
    username, password := utils_os_args.GetArg2s()
    fmt.Println("username:", username)

    // (1) 连接服务器
    // 连接到IMAP服务器
    c, err := client.DialTLS("imap.163.com:993", nil)
    done.Done(err)
    defer func(c *client.Client) {
        _ = c.Logout()
    }(c)

    fmt.Println("state:", c.State())

    // (2) 登录邮箱
    // 登录到邮箱
    done.Done(c.Login(username, password))
    fmt.Println("state:", c.State())

    // (3) 添加ID信息(以防收取163邮箱报错(error): SELECT Unsafe Login. Please contact kefu@188.com for help)
    // 设置客户端ID
    serverID, err := imapID.NewClient(c).ID(imapID.ID{
        imapID.FieldName:    "IMAPClient",
        imapID.FieldVersion: "3.1.0",
    })
    done.Done(err)
    fmt.Println("serverID:", softjson.NeatString(serverID))

    {
        // 选择收件箱
        mbox, err := c.Select("INBOX", false)
        done.Done(err)
        fmt.Println("inbox.name:", mbox.Name)

        // 获取收件箱中的所有邮件序列号
        seqSet := new(imap.SeqSet)
        seqSet.AddRange(1, mbox.Messages)
        fmt.Println("inbox_messages_index:", 1, mbox.Messages)

        if mbox.Messages <= 0 {
            //假如实际有邮件但提示没有邮件,有可能是你设置的仅仅“收取最近30天邮件”,因此稍微老点的邮件都收不到
            fmt.Println("收件箱里没有邮件")
            //return
        } else {
            storeItem := imap.FormatFlagsOp(imap.AddFlags, true)
            flags := []interface{}{imap.DeletedFlag}
            err = c.Store(seqSet, storeItem, flags, nil)
            done.Done(err)
            fmt.Println("收件箱已标记为删除-移动到垃圾箱")

            err = c.Expunge(nil)
            done.Done(err)
            fmt.Println("已删除的邮件已清空")
        }

        err = c.Expunge(nil)
        done.Done(err)
    }
    {
        // 选择垃圾箱
        mbox, err := c.Select("TRASH", false)
        done.Done(err)
        fmt.Println("inbox.name:", mbox.Name)
        fmt.Println("inbox_messages_index:", 1, mbox.Messages)

        var ch = make(chan uint32, mbox.Messages)
        for i := uint32(1); i <= mbox.Messages; i++ {
            ch <- i
        }

        fmt.Println(len(ch))
        err = c.Expunge(ch)
        done.Done(err)
        fmt.Println("已删除的邮件已清空")
    }
}