From 3c6bd8ede3395c49df6125255b93ec0fa8d4aa71 Mon Sep 17 00:00:00 2001 From: jh_peng Date: Tue, 29 Oct 2024 11:18:12 +0800 Subject: [PATCH] =?UTF-8?q?V0=20=E7=BB=93=E6=89=B9=E6=8A=A5=E5=91=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- initialization/cron.go | 16 ++ main.go | 1 + repository/test.data/report.excel.go | 2 + request/report.excel.go | 1 + utils/email.go | 219 +++++++++++++++++++++++++++ 5 files changed, 239 insertions(+) create mode 100644 utils/email.go diff --git a/initialization/cron.go b/initialization/cron.go index 787c14b..c5bd9db 100644 --- a/initialization/cron.go +++ b/initialization/cron.go @@ -7,6 +7,7 @@ import ( "log" "testData/global" test_data "testData/repository/test.data" + "testData/utils" ) func InitCronListCron() { @@ -28,3 +29,18 @@ func InitCronListCron() { } c.Start() } + +func InitEmailCron() { + c := cron.New(cron.WithChain(cron.SkipIfStillRunning(cron.DefaultLogger))) + //_, err := c.AddFunc("0 */1 * * *", func() { + _, err := c.AddFunc("*/30 * * * *", func() { + fmt.Println(carbon.Now().Format("Y-m-d H:i:s") + "EmailCron start") + utils.Emails() + fmt.Println(carbon.Now().Format("Y-m-d H:i:s") + "EmailCron finish") + }) + if err != nil { + global.Log.Errorf("InitEmailCron AddFunc error: %s", err) + log.Fatalln(err) + } + c.Start() +} diff --git a/main.go b/main.go index bdfcc7e..c2c40f8 100644 --- a/main.go +++ b/main.go @@ -28,6 +28,7 @@ func main() { //report_reader.FTSMCReportReader("./SMC-3月.xlsx") initialization.InitCronListCron() + //initialization.InitEmailCron() //var fileHandles []*model.FileHandled //global.PostGreSQL.Where("lot = ? AND step = ?", "S3S592", "FT").Find(&fileHandles) diff --git a/repository/test.data/report.excel.go b/repository/test.data/report.excel.go index 7e1e10c..03e747f 100644 --- a/repository/test.data/report.excel.go +++ b/repository/test.data/report.excel.go @@ -20,6 +20,7 @@ func CreateFinalReportExcel(req *request.CreateFinalReportExcel) error { PBI: req.PBI, OrderDate: req.OrderDate, Seal: req.Seal, + SubBatch: req.SubBatch, FinalTestQuantity: req.FinalTestQuantity, FinalPassQuantity: req.FinalPassQuantity, FinalPassProbability: req.FinalPassProbability, @@ -59,6 +60,7 @@ func UpdateFinalReportExcel(req *request.UpdateFinalReportExcel) error { "step": req.Step, "product": req.Product, "lot": req.Lot, + "sub_batch": req.SubBatch, "factory": req.Factory, "test_program": req.TestProgram, "pbi": req.PBI, diff --git a/request/report.excel.go b/request/report.excel.go index 1364e15..5e51fa0 100644 --- a/request/report.excel.go +++ b/request/report.excel.go @@ -4,6 +4,7 @@ type CreateFinalReportExcel struct { Step string `json:"step"` // 工序 Product string `json:"product"` // 成品型号 Lot string `json:"lot"` // 晶圆批次 + SubBatch string `json:"sub_batch"` // 子批次 Factory string `json:"factory"` // 测试厂 TestProgram string `json:"test_program"` // 测试程序 PBI string `json:"pbi"` // PBI diff --git a/utils/email.go b/utils/email.go new file mode 100644 index 0000000..898623a --- /dev/null +++ b/utils/email.go @@ -0,0 +1,219 @@ +package utils + +import ( + "fmt" + "github.com/emersion/go-imap" + "github.com/emersion/go-imap/client" + "github.com/emersion/go-message/charset" + "github.com/emersion/go-message/mail" + "github.com/xuri/excelize/v2" + "io" + "io/ioutil" + "log" + "os" + "path/filepath" + "strconv" + "strings" + "testData/global" + "testData/repository/report_reader" + "time" +) + +func Emails() { + fmt.Println("Connecting to server...") + + // Connect to server + c, err := client.DialTLS("imap.exmail.qq.com:993", nil) + if err != nil { + fmt.Println("连接IMAP服务器出错:", err) + return + } + fmt.Println("Connected QQ Imap Receive Server(imap.exmail.qq.com)...") + + // Login + if err = c.Login("wip@tkplusemi.com", "Tkpluse123ip"); err != nil { + fmt.Println("登陆IMAP服务器出错:", err) + return + } + //if err := c.Login("jh_peng@tkplusemi.com", "Jimmy123"); err != nil { + // log.Fatal(err) + //} + fmt.Println("Logged in...") + + global.IMAP = c + + // List mailboxes + mailboxes := make(chan *imap.MailboxInfo, 10) + done := make(chan error, 10) + go func() { + done <- global.IMAP.List("", "*", mailboxes) + }() + log.Println("Mailboxes:") + for m := range mailboxes { + fmt.Println("* " + m.Name) + } + + if err := <-done; err != nil { + fmt.Println(err) + } + + // Select INBOX + mbox, err := global.IMAP.Select("INBOX", false) + if err != nil { + fmt.Println(err) + } + fmt.Println("mbox:", mbox) + //fmt.Println("Flags for INBOX:", mbox.Flags) + + // 创建搜索条件 + criteria := imap.NewSearchCriteria() + // 搜索未读标志的邮件 + criteria.WithoutFlags = []string{"\\Seen"} + // 获取未读标志邮件的UID + ids, _ := global.IMAP.UidSearch(criteria) + // 按UID获取邮件 + seqset := new(imap.SeqSet) + seqset.AddNum(ids...) + + // 获取邮件 + messages := make(chan *imap.Message) + section := imap.BodySectionName{} + // 获取邮件标志, 内容 + items := []imap.FetchItem{imap.FetchFlags, section.FetchItem()} + done = make(chan error, len(ids)) + go func() { + // 按UID获取邮件 + done <- global.IMAP.UidFetch(seqset, items, messages) + }() + + imap.CharsetReader = charset.Reader + for msg := range messages { + start := time.Now() + r := msg.GetBody(§ion) + if r == nil { + log.Println("服务器未返回邮件正文") + } + fmt.Printf("获取邮件内容耗时:%s\n", time.Now().Sub(start).String()) + mr, err := mail.CreateReader(r) + if err != nil { + log.Fatal(err) + } + header := mr.Header + var subject string + var company string + // 获取邮件发件人 + if from, err := header.AddressList("From"); err == nil { + fmt.Println(from[0].Address) + startFrom := time.Now() + address := from[0].Address + if orgsender, err := header.AddressList("X-Qq-Csender"); err == nil { // X-Qq-Orgsender + if len(orgsender) > 0 && orgsender[0].Address != "" { + address = orgsender[0].Address + } + } + if len(from) != 1 { + fmt.Printf("当前邮件耗时:%s\n", time.Now().Sub(start).String()) + fmt.Printf("当前邮件处理From耗时:%s\n", time.Now().Sub(startFrom).String()) + continue + } + var needHandle bool + if address == "crmic_smc_atm_zy@smc.crmicro.com" { + // 获取邮件主题 + if subject, err = header.Subject(); err == nil { + if strings.Contains(subject, "J106397_FT") { + company = "华润赛美科" + needHandle = true + } + } + } + if !needHandle { + fmt.Printf("当前邮件耗时:%s\n", time.Now().Sub(start).String()) + fmt.Printf("当前邮件处理From耗时:%s\n", time.Now().Sub(startFrom).String()) + continue + } + log.Println("From:", from) + } + // 处理邮件正文 + for { + p, err := mr.NextPart() + if err == io.EOF { + break + } else if err != nil { + log.Fatal("NextPart:err ", err) + } + switch h := p.Header.(type) { + case *mail.AttachmentHeader: + // 正文内附件 + b, _ := ioutil.ReadAll(p.Body) + filename, _ := h.Filename() + var a []byte + p.Body.Read(a) + suffixIndex := strings.LastIndex(filename, ".") + suffix := strings.ToLower(filename[suffixIndex:]) + filename = filename[:suffixIndex] + suffix + //if !strings.Contains(filename, ".xlsx") && !strings.Contains(filename, ".xls") && !strings.Contains(filename, ".CSV") { + // continue + //} + if suffix != ".xlsx" && suffix != ".xls" && suffix != ".csv" { + continue + } + + // 根据公司名生成文件路径 + folderPath := MakeSavePath(company) + var newFileName string + if strings.Contains(filename, ".xlsx") { + newFileName = filepath.Join(folderPath, time.Now().Format("20060102150405.xlsx")) + f, _ := os.OpenFile(newFileName, os.O_RDWR|os.O_CREATE, 0766) + _, err = f.Write(b) + if err != nil { + log.Println("download file", filename, "err") + _ = os.Remove(filename) + } + f.Close() + } else if strings.Contains(filename, ".xls") { + newFileName = filepath.Join(folderPath, time.Now().Format("20060102150405.xls")) + f, _ := os.OpenFile(newFileName, os.O_RDWR|os.O_CREATE, 0766) + _, err = f.Write(b) + if err != nil { + log.Println("download file", filename, "err") + _ = os.Remove(filename) + } + _ = f.Close() + ToXlsx("xls", newFileName) + newFileName += ".xlsx" + } else if strings.Contains(filename, ".csv") { + newFileName = filepath.Join(folderPath, time.Now().Format("20060102150405.xlsx")) + rows := strings.Split(string(b), "\r\n") + f := excelize.NewFile() + // 获取Sheet工作表名称 + sheetName := f.GetSheetName(0) + for i := 0; i < len(rows); i++ { + columns := strings.Split(rows[i], ",") + _ = f.SetSheetRow(sheetName, string(byte(65))+strconv.Itoa(i+1), &columns) + } + _ = f.SaveAs(newFileName) + _ = f.Close() + } + // 处理Excel + switch company { + case "华润赛美科": + report_reader.FTSMCReportReader(newFileName) + } + fmt.Printf("当前邮件耗时:%s\n", time.Now().Sub(start).String()) + default: + fmt.Printf("当前邮件耗时:%s\n", time.Now().Sub(start).String()) + continue + } + } + } + // 添加标志 + item := imap.FormatFlagsOp(imap.AddFlags, true) + // 已读标志\Seen + flags := []interface{}{imap.SeenFlag} + // 将处理的未读邮件设置为已读 + err = global.IMAP.UidStore(seqset, item, flags, nil) + if err != nil { + log.Println(err) + } + global.IMAP.Logout() +}