コード例 #1
0
ファイル: email.go プロジェクト: jeremyschlatter/email-viewer
func fetch(c *imap.Client, user string, thread Thread) ([]*ParsedMail, error) {
	var set imap.SeqSet
	for _, uid := range thread {
		set.AddNum(uid)
	}
	cmd, err := imap.Wait(c.UIDFetch(&set, "BODY[]", "X-GM-MSGID", "X-GM-THRID"))
	if err != nil {
		return nil, ErrBadConnection
	}
	parsed := make([]*ParsedMail, len(cmd.Data))
	for i, rsp := range cmd.Data {
		p, err := parseMail(imap.AsBytes(rsp.MessageInfo().Attrs["BODY[]"]), user)
		if err != nil {
			return nil, err
		}
		link, err := gmailLink(imap.AsString(rsp.MessageInfo().Attrs["X-GM-MSGID"]))
		if err != nil {
			return nil, err
		}
		p.GmailLink = link
		p.Thrid = imap.AsString(rsp.MessageInfo().Attrs["X-GM-THRID"])
		parsed[i] = p
	}
	return parsed, nil
}
コード例 #2
0
ファイル: eazye.go プロジェクト: jprobinson/eazye
// newEmailMessage will parse an imap.FieldMap into an Email. This
// will expect the message to container the internaldate and the body with
// all headers included.
func newEmail(msgFields imap.FieldMap) (Email, error) {
	var email Email
	// parse the header
	var message bytes.Buffer
	message.Write(imap.AsBytes(msgFields["RFC822.HEADER"]))
	message.Write([]byte("\n\n"))
	rawBody := imap.AsBytes(msgFields["BODY[]"])
	message.Write(rawBody)
	msg, err := mail.ReadMessage(&message)
	if err != nil {
		return email, fmt.Errorf("unable to read header: %s", err)
	}

	from, err := mail.ParseAddress(msg.Header.Get("From"))
	if err != nil {
		return email, fmt.Errorf("unable to parse from address: %s", err)
	}

	to, err := mail.ParseAddressList(msg.Header.Get("To"))
	if err != nil {
		return email, fmt.Errorf("unable to parse to address: %s", err)
	}

	email = Email{
		Message:      msg,
		InternalDate: imap.AsDateTime(msgFields["INTERNALDATE"]),
		Precedence:   msg.Header.Get("Precedence"),
		From:         from,
		To:           to,
		Subject:      parseSubject(msg.Header.Get("Subject")),
	}

	// chunk the body up into simple chunks
	email.HTML, email.Text, email.IsMultiPart, err = parseBody(msg.Header, rawBody)
	return email, err
}
コード例 #3
0
ファイル: imapSource.go プロジェクト: hoffie/lemoncrypt
// invokeMessageCallback extracts the relevant data from the passed FETCH response
// and invokes the user-provided callback.
func (w *IMAPSource) invokeMessageCallback(msgInfo *imap.MessageInfo) error {
	logger.Debugf("handling mail uid=%d", msgInfo.Attrs["UID"])
	flags := imap.AsFlagSet(msgInfo.Attrs["FLAGS"])
	idate := imap.AsDateTime(msgInfo.Attrs["INTERNALDATE"])
	mailBytes := imap.AsBytes(msgInfo.Attrs["RFC822"])
	mailLiteral := imap.NewLiteral(mailBytes)
	logger.Debugf("invoking message transformer")
	err := w.callbackFunc(flags, &idate, mailLiteral)
	if err == nil {
		logger.Debugf("message transformation successful")
	} else {
		logger.Warningf("message transformation failed: %s", err)
	}
	return err
}
コード例 #4
0
ファイル: fromEmail.go プロジェクト: harrisj/streamtools
// newEmailMessage will parse an imap.FieldMap into an map[string]interface{}. This
// will expect the message to container the internaldate and the body with
// all headers included.
func newEmailMessage(msgFields imap.FieldMap) (map[string]interface{}, error) {
	var email map[string]interface{}
	// parse the header
	rawHeader := imap.AsBytes(msgFields["RFC822.HEADER"])
	msg, err := mail.ReadMessage(bytes.NewReader(rawHeader))
	if err != nil {
		return email, err
	}

	email = map[string]interface{}{
		"internal_date": imap.AsDateTime(msgFields["INTERNALDATE"]),
		"body":          imap.AsString(msgFields["BODY[]"]),
		"from":          msg.Header.Get("From"),
		"to":            msg.Header.Get("To"),
		"subject":       msg.Header.Get("Subject"),
	}

	return email, nil
}
コード例 #5
0
ファイル: main.go プロジェクト: gmap-notifier/gmap_notifier
func notifyNewEmail(c *imap.Client, mId uint32) {
	set, _ := imap.NewSeqSet("")
	set.AddNum(mId)
	cmd := ReportOK(c.Fetch(set, "FLAGS", "RFC822.HEADER"))
	for _, rsp := range cmd.Data {
		header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
		if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
			subj := msg.Header.Get("Subject")
			from := msg.Header.Get("From")
			formattedFrom := strings.Split(from, " ")[0]
			exec.Command(
				"terminal-notifier",
				"-message", subj,
				"-title", "Mail From: "+formattedFrom+"",
				"-sender", "com.apple.Mail",
			).Output()
		}
	}
}
コード例 #6
0
ファイル: attachy.go プロジェクト: xunien/attachy
// fetchMessage send UID FETCH command to retrieve message body
func fetchMessage(client *imap.Client, messageUID uint32) ([]byte, error) {
	seq := new(imap.SeqSet)

	seq.AddNum(messageUID)
	cmd, err := imap.Wait(client.UIDFetch(seq, "INTERNALDATE", "BODY[]", "UID", "RFC822.HEADER"))

	if err != nil {
		logger.Errorf("Unable to fetch message (%d): %s", messageUID, err.Error())
		return nil, nil
	}

	if len(cmd.Data) == 0 {
		logger.WithField("uid", messageUID).Info("Unable to fetch message from src: NO DATA")
		return nil, errors.New("message not found")
	}

	msgFields := cmd.Data[0].MessageInfo().Attrs
	body := imap.AsBytes(msgFields["BODY[]"])

	cmd.Data = nil

	return body, nil
}
コード例 #7
0
ファイル: rest_email.go プロジェクト: yuanlv/learning-in-go
func (emaill *Email) getEmailContentUseIMAP(w rest.ResponseWriter, r *rest.Request) {
	addr := r.FormValue("imapAddr")
	port := r.FormValue("imapPort")
	user := r.FormValue("user")
	pwd := r.FormValue("pwd")
	id := r.FormValue("id")

	address := addr + ":" + port
	log.Printf("get email content use imap %s\n", address)

	var (
		c   *imap.Client
		cmd *imap.Command
		rsp *imap.Response
	)

	// Connect to the server
	c, err := imap.Dial(addr)
	if err != nil {
		log.Printf("dial %s error\n", address)
		return
	}

	// Remember to log out and close the connection when finished
	defer c.Logout(30 * time.Second)

	// Print server greeting (first response in the unilateral server data queue)
	log.Printf("Server says hello:%s", c.Data[0].Info)
	c.Data = nil

	// Enable encryption, if supported by the server
	if c.Caps["STARTTLS"] {
		c.StartTLS(nil)
	}

	// Authenticate
	if c.State() == imap.Login {
		c.Login(user, pwd)
	}

	// List all top-level mailboxes, wait for the command to finish
	cmd, _ = imap.Wait(c.List("", "%"))

	// Print mailbox information
	log.Printf("\nTop-level mailboxes:")
	for _, rsp = range cmd.Data {
		log.Printf("|--%s", rsp.MailboxInfo())
	}

	// Check for new unilateral server data responses
	for _, rsp = range c.Data {
		log.Printf("Server data:%s", rsp)
	}
	c.Data = nil

	// Open a mailbox (synchronous command - no need for imap.Wait)
	c.Select("INBOX", true)
	log.Printf("\nMailbox status:%s\n", c.Mailbox)
	if c.Mailbox == nil {
		resp := EmailJsonResponse{Success: true}
		w.WriteJson(&resp)
		return
	}

	// Fetch the headers of the 10 most recent messages
	set, _ := imap.NewSeqSet("")
	set.Add(id)
	// if c.Mailbox.Messages >= 10 {
	// 	set.AddRange(c.Mailbox.Messages-9, c.Mailbox.Messages) //测试只取最新一封邮件
	// } else {
	// 	set.Add("1:*")
	// }
	cmd, _ = c.Fetch(set, "RFC822.HEADER", "RFC822.TEXT") //指定要获取的内容

	// Process responses while the command is running
	log.Printf("\nget mail [%s] messages:", id)
	for cmd.InProgress() {
		// Wait for the next response (no timeout)
		c.Recv(-1)

		// Process command data
		for _, rsp = range cmd.Data {
			header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
			if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
				subject := msg.Header.Get("Subject")
				log.Printf("|--%s", subject)

				realSubject := GetRealSubject(subject)
				log.Printf("in rest_email.go: get real subject")
				log.Printf(realSubject)

				senderAddr := msg.Header.Get("From")
				recverAddrList := msg.Header.Get("To")

				realSenderAddr := GetRealSubject(senderAddr)
				realRecverAddrList := GetRealSubject(recverAddrList)

				body := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.TEXT"])
				//log.Printf("email body: %s", body)
				//realBody  := GetRealBody(string(body))
				headerAndBody := make([]byte, len(header)+len(body))
				copy(headerAndBody, header)
				copy(headerAndBody[len(header):], body)

				msg, _ := mail.ReadMessage(bytes.NewReader(headerAndBody))
				mime, _ := enmime.ParseMIMEBody(msg)
				realBody := mime.Text //如果原始内容为html,会去掉html元素标签
				log.Printf("real body: %s", realBody)

				//获取MIMEPart所有节点内容
				// log.Printf("root ======================")
				// root := mime.Root
				// if root != nil {
				// 	log.Printf(string(root.Content()))
				// 	log.Printf("child==========")
				// 	if child := root.FirstChild(); child != nil {
				// 		log.Printf(string(child.Content()))
				// 	}

				// }

				attachments := mime.Attachments
				log.Printf("attachments len=%d", len(attachments))
				count := len(attachments)
				var attachmentList []Attachment = nil
				var data EmailContent
				if count > 0 {
					attachmentList = make([]Attachment, count)
					for i := 0; i < len(attachments); i++ {
						name := attachments[i].FileName()
						content := attachments[i].Content() //todo encode by base64
						log.Printf("name===%s", name)
						attachmentList[i] = Attachment{Name: name, Body: string(content)}
					}

				}
				data = EmailContent{Subject: realSubject, SenderAddr: realSenderAddr,
					RecverAddrList: realRecverAddrList, Content: realBody,
					Attachments: attachmentList}

				resp := EmailJsonResponse{Success: true, Data: data}
				w.WriteJson(resp)
			}
		}
		cmd.Data = nil

		// Process unilateral server data
		for _, rsp = range c.Data {
			log.Printf("Server data:%s", rsp)
		}
		c.Data = nil
	}

	// Check command completion status
	if rsp, err := cmd.Result(imap.OK); err != nil {
		if err == imap.ErrAborted {
			log.Printf("Fetch command aborted\n")
		} else {
			log.Printf("Fetch error:%s\n", rsp.Info)
		}
	}

}
コード例 #8
0
ファイル: updateTray.go プロジェクト: jonhoo/hasmail
// updateTray is called whenever a client detects that the number of unseen
// messages *may* have changed. It will search the selected folder for unseen
// messages, count them and store the result. Then it will use the notify
// channel to let our main process update the status icon.
func UpdateTray(c *imap.Client, notify chan bool, name string) {
	// Send > Search since Search adds CHARSET UTF-8 which might not be supported
	cmd, err := c.Send("SEARCH", "UNSEEN")

	if err != nil {
		fmt.Printf("%s failed to look for new messages\n", name)
		fmt.Println("  ", err)
		return
	}

	if _, ok := Unseen[name]; !ok {
		Unseen[name] = []uint32{}
	}

	unseenMessages := []uint32{}
	for cmd.InProgress() {
		// Wait for the next response (no timeout)
		err = c.Recv(-1)

		// Process command data
		for _, rsp := range cmd.Data {
			result := rsp.SearchResults()
			unseenMessages = append(unseenMessages, result...)
		}

		// Reset for next run
		cmd.Data = nil
		c.Data = nil
	}

	// Check command completion status
	if rsp, err := cmd.Result(imap.OK); err != nil {
		if err == imap.ErrAborted {
			fmt.Println("fetch command aborted")
		} else {
			fmt.Println("fetch error:", rsp.Info)
		}

		return
	}

	fmt.Printf("%d unseen\n", len(unseenMessages))

	// Find messages that the user hasn't been notified of
	// TODO: Make this optional/configurable
	newUnseen, _ := imap.NewSeqSet("")
	numNewUnseen := 0
	for _, uid := range unseenMessages {
		seen := false
		for _, olduid := range Unseen[name] {
			if olduid == uid {
				seen = true
				break
			}
		}

		if !seen {
			newUnseen.AddNum(uid)
			numNewUnseen++
		}
	}

	// If we do have new unseen messages, fetch and display them
	if numNewUnseen > 0 {
		messages := make([]string, numNewUnseen)
		i := 0

		// Fetch headers...
		cmd, _ = c.Fetch(newUnseen, "RFC822.HEADER")
		for cmd.InProgress() {
			c.Recv(-1)
			for _, rsp := range cmd.Data {
				header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
				if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
					subject := msg.Header.Get("Subject")
					messages[i], err = new(mime.WordDecoder).DecodeHeader(subject)
					if err != nil {
						messages[i] = subject
					}
					i++
				}
			}

			cmd.Data = nil
			c.Data = nil
		}

		// Print them in reverse order to get newest first
		notification := ""
		for ; i > 0; i-- {
			notification += "> " + messages[i-1] + "\n"
		}
		notification = strings.TrimRight(notification, "\n")
		fmt.Println(notification)

		// And send them with notify-send!
		title := fmt.Sprintf("%s has new mail (%d unseen)", name, len(unseenMessages))
		sh := exec.Command("/usr/bin/notify-send",
			"-i", "notification-message-email",
			"-c", "email",
			title, notification)

		err := sh.Start()
		if err != nil {
			fmt.Println("Failed to notify user...")
			fmt.Println(err)
		}
		go func() {
			// collect exit code to avoid zombies
			sh.Wait()
		}()
	}

	Unseen[name] = unseenMessages

	// Let main process know something has changed
	notify <- true
}
コード例 #9
0
ファイル: mailbot.go プロジェクト: elangenhan/mailbot
func main() {
	token := flag.String("token", "", "The Telegram bot token")
	to := flag.String("to", "", "The mail recipient")
	from := flag.String("from", "", "The mail sender")
	server := flag.String("server", "", "The mail server")
	port := flag.Int("port", 587, "The mail server port")
	user := flag.String("user", "", "")
	pass := flag.String("pass", "", "")
	subject := flag.String("subject", "", "")

	flag.Parse()

	bot, err := telebot.NewBot(*token)
	if err != nil {
		return
	}

	// Fetching Mails and send as Telegram messages

	var (
		c   *imap.Client
		cmd *imap.Command
		rsp *imap.Response
	)

	c, _ = imap.Dial(*server)

	defer c.Logout(30 * time.Second)

	c.Data = nil

	if c.Caps["STARTTLS"] {
		c.StartTLS(nil)
	}

	if c.State() == imap.Login {
		c.Login(*user, *pass)
	}

	cmd, _ = imap.Wait(c.List("", "%"))

	c.Data = nil

	c.Select("INBOX", true)

	set, _ := imap.NewSeqSet("")
	set.Add("1:*")
	cmd, _ = c.Fetch(set, "RFC822.HEADER")

	for cmd.InProgress() {
		c.Recv(-1)

		for _, rsp = range cmd.Data {
			header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
			if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
				fmt.Println("|--", msg.Header.Get("FROM"))
			}
		}
		cmd.Data = nil
		c.Data = nil
	}

	if rsp, err := cmd.Result(imap.OK); err != nil {
		if err == imap.ErrAborted {
			fmt.Println("Fetch command aborted")
		} else {
			fmt.Println("Fetch error:", rsp.Info)
		}
	}

	/*
	 * Listen to Telegram messages and send as mail
	 */

	messages := make(chan telebot.Message)
	bot.Listen(messages, 1*time.Second)

	for message := range messages {

		m := gomail.NewMessage()
		m.SetHeader("From", *from)
		m.SetHeader("To", *to)
		m.SetHeader("Subject", *subject)
		m.SetBody("text/html", message.Text)

		d := gomail.NewPlainDialer(*server, *port, *user, *pass)
		d.TLSConfig = &tls.Config{InsecureSkipVerify: true}

		if err := d.DialAndSend(m); err != nil {
			panic(err)
		}
	}
}
コード例 #10
0
// CheckNewMails Check if exist a new mail and post it
func (m *MatterMail) CheckNewMails() error {
	m.debg.Println("CheckNewMails")

	if err := m.CheckImapConnection(); err != nil {
		return err
	}

	var (
		cmd *imap.Command
		rsp *imap.Response
	)

	// Open a mailbox (synchronous command - no need for imap.Wait)
	m.imapClient.Select("INBOX", false)

	var specs []imap.Field
	specs = append(specs, "UNSEEN")
	seq := &imap.SeqSet{}

	// get headers and UID for UnSeen message in src inbox...
	cmd, err := imap.Wait(m.imapClient.UIDSearch(specs...))
	if err != nil {
		m.debg.Println("Error UIDSearch UTF-8:")
		m.debg.Println(err)
		m.debg.Println("Try with US-ASCII")

		// try again with US-ASCII
		cmd, err = imap.Wait(m.imapClient.Send("UID SEARCH", append([]imap.Field{"CHARSET", "US-ASCII"}, specs...)...))
		if err != nil {
			m.eror.Println("UID SEARCH US-ASCII")
			return err
		}
	}

	for _, rsp := range cmd.Data {
		for _, uid := range rsp.SearchResults() {
			m.debg.Println("CheckNewMails:AddNum ", uid)
			seq.AddNum(uid)
		}
	}

	// no new messages
	if seq.Empty() {
		m.debg.Println("CheckNewMails: No new messages")
		return nil
	}

	cmd, _ = m.imapClient.UIDFetch(seq, "BODY[]")
	postmail := false

	for cmd.InProgress() {
		m.debg.Println("CheckNewMails: cmd in Progress")
		// Wait for the next response (no timeout)
		m.imapClient.Recv(-1)

		// Process command data
		for _, rsp = range cmd.Data {
			msgFields := rsp.MessageInfo().Attrs
			header := imap.AsBytes(msgFields["BODY[]"])
			if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
				m.debg.Println("CheckNewMails:PostMail")
				if err := m.PostMail(msg); err != nil {
					return err
				}
				postmail = true
			}
		}
		cmd.Data = nil
	}

	// Check command completion status
	if rsp, err := cmd.Result(imap.OK); err != nil {
		if err == imap.ErrAborted {
			m.eror.Println("Fetch command aborted")
			return err
		}
		m.eror.Println("Fetch error:", rsp.Info)
		return err
	}

	cmd.Data = nil

	if postmail {
		m.debg.Println("CheckNewMails: Mark all messages with flag \\Seen")

		//Mark all messages seen
		_, err = imap.Wait(m.imapClient.UIDStore(seq, "+FLAGS.SILENT", `\Seen`))
		if err != nil {
			m.eror.Println("Error UIDStore \\Seen")
			return err
		}
	}

	return nil
}
コード例 #11
0
ファイル: fetcher.go プロジェクト: hochhaus/mammothmail
// Fetch email for the specified user and host.
func Fetch(host, user, pass string) {
	c, err := imap.Dial(host)
	if err != nil {
		log.Print(err)
		return
	}
	defer c.Logout(30 * time.Second)

	log.Println("Server says hello:", c.Data[0].Info)
	c.Data = nil

	if c.Caps["STARTTLS"] {
		c.StartTLS(nil)
	}

	if c.State() == imap.Login {
		c.Login(user, pass)
	}

	cmd, err := imap.Wait(c.List("", "%"))
	if err != nil {
		log.Print(err)
		return
	}

	log.Println("\nTop-level mailboxes:")
	for _, rsp := range cmd.Data {
		log.Println("|--", rsp.MailboxInfo())
	}

	for _, rsp := range c.Data {
		log.Println("Server data:", rsp)
	}
	c.Data = nil

	c.Select("INBOX", true)
	log.Print("\nMailbox status:\n", c.Mailbox)

	set, _ := imap.NewSeqSet("")
	if c.Mailbox.Messages >= 10 {
		set.AddRange(c.Mailbox.Messages-9, c.Mailbox.Messages)
	} else {
		set.Add("1:*")
	}
	cmd, _ = c.Fetch(set, "RFC822.HEADER")

	log.Println("\nMost recent messages:")
	for cmd.InProgress() {
		// Wait for the next response (no timeout)
		c.Recv(-1)

		// Process command data
		for _, rsp := range cmd.Data {
			header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
			if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
				log.Println("|--", msg.Header.Get("Subject"))
			}
		}
		cmd.Data = nil

		// Process unilateral server data
		for _, rsp := range c.Data {
			log.Println("Server data:", rsp)
		}
		c.Data = nil
	}

	if rsp, err := cmd.Result(imap.OK); err != nil {
		if err == imap.ErrAborted {
			log.Println("Fetch command aborted")
		} else {
			log.Println("Fetch error:", rsp.Info)
		}
	}
}
コード例 #12
0
ファイル: mailporter.go プロジェクト: 12foo/wiwi-mailporter
func transferMbox(c *cli.Context) {
	source := c.Args().Get(0)
	target := c.Args().Get(1)
	if source == "" || target == "" {
		log.Fatal("Bitte Quell- und Zielordner angeben, z.B.: mailporter transfer INBOX INBOX")
	}
	n := imapConnect(notes)
	defer n.Logout(30 * time.Second)
	_, err := n.Select(source, true)
	if err != nil {
		log.Fatal("Kein Zugriff auf %s/%s. Fehler: %s", notes, source, err.Error())
	}
	e := imapConnect(exchange)
	defer e.Logout(30 * time.Second)

	fmt.Println("Ermittle zu übertragende Mails...")
	criteria := []string{"ALL"}
	if c.String("before") != "" {
		criteria = append(criteria, "BEFORE "+c.String("before"))
	}
	nc, err := imap.Wait(n.UIDSearch(strings.Join(criteria, " ")))
	var mails []uint32
	for _, r := range nc.Data {
		mails = r.SearchResults()
	}
	reader := bufio.NewReader(os.Stdin)
	fmt.Printf("%d Mails sind zu übertragen. Fortfahren (j oder n)? ", len(mails))
	cont, _ := reader.ReadString('\n')
	if strings.TrimSpace(cont) != "j" {
		return
	}
	fmt.Printf("Übertrage Mails.\n")
	bar := pb.StartNew(len(mails))
	set, _ := imap.NewSeqSet("")
	for _, mid := range mails {
		set.AddNum(mid)
	}
	fetch, err := n.UIDFetch(set, "BODY.PEEK[]")
	if err != nil {
		log.Fatalf("Konnte Mails nicht laden: ", err)
	}
	flags := map[string]bool{
		"\\Seen": true,
	}
	for fetch.InProgress() {
		n.Recv(-1)
		for _, r := range fetch.Data {
			i := r.MessageInfo()
			if i.Size >= maxSize {
				m, err := mail.ReadMessage(bytes.NewReader(imap.AsBytes(i.Attrs["BODY[]"])))
				if err != nil {
					log.Fatal(err)
				}
				date, _ := m.Header.Date()
				datestring := date.Format(time.RFC822)
				fmt.Printf("WARNUNG: Mail '%s' (%s, von %s) ist zu groß für Exchange. Überspringe.\n",
					m.Header.Get("Subject"), datestring, m.Header.Get("From"))
				fetch.Data = nil
				n.Data = nil
				continue
			}
			_, err := imap.Wait(e.Append(target, flags, nil,
				imap.NewLiteral(imap.AsBytes(i.Attrs["BODY[]"]))))
			if err != nil {
				fmt.Printf("WARNUNG: Konnte Mail nicht auf Exchange speichern.\nFehler: %s\n", err.Error())
				m, err := mail.ReadMessage(bytes.NewReader(imap.AsBytes(i.Attrs["BODY[]"])))
				if err != nil {
					log.Fatal(err)
				}
				date, _ := m.Header.Date()
				datestring := date.Format(time.RFC822)
				fmt.Println("Von: ", m.Header.Get("From"))
				fmt.Println("Betreff: ", m.Header.Get("Subject"))
				fmt.Println("Datum: ", datestring)
				e.Logout(0)
				e = imapConnect(exchange)
				defer e.Logout(30 * time.Second)
				fetch.Data = nil
				n.Data = nil
				continue
			}
			bar.Increment()
		}
		fetch.Data = nil
		n.Data = nil
	}
}
コード例 #13
0
ファイル: example_test.go プロジェクト: jappre/mutation
func ExampleClient() {
	//
	// Note: most of error handling code is omitted for brevity
	//
	var (
		c   *imap.Client
		cmd *imap.Command
		rsp *imap.Response
	)

	// Connect to the server
	c, _ = imap.Dial("imap.example.com")

	// Remember to log out and close the connection when finished
	defer c.Logout(30 * time.Second)

	// Print server greeting (first response in the unilateral server data queue)
	fmt.Println("Server says hello:", c.Data[0].Info)
	c.Data = nil

	// Enable encryption, if supported by the server
	if c.Caps["STARTTLS"] {
		c.StartTLS(nil)
	}

	// Authenticate
	if c.State() == imap.Login {
		c.Login("*****@*****.**", "mysupersecretpassword")
	}

	// List all top-level mailboxes, wait for the command to finish
	cmd, _ = imap.Wait(c.List("", "%"))

	// Print mailbox information
	fmt.Println("\nTop-level mailboxes:")
	for _, rsp = range cmd.Data {
		fmt.Println("|--", rsp.MailboxInfo())
	}

	// Check for new unilateral server data responses
	for _, rsp = range c.Data {
		fmt.Println("Server data:", rsp)
	}
	c.Data = nil

	// Open a mailbox (synchronous command - no need for imap.Wait)
	c.Select("INBOX", true)
	fmt.Print("\nMailbox status:\n", c.Mailbox)

	// Fetch the headers of the 10 most recent messages
	set, _ := imap.NewSeqSet("")
	if c.Mailbox.Messages >= 10 {
		set.AddRange(c.Mailbox.Messages-9, c.Mailbox.Messages)
	} else {
		set.Add("1:*")
	}
	cmd, _ = c.Fetch(set, "RFC822.HEADER")

	// Process responses while the command is running
	fmt.Println("\nMost recent messages:")
	for cmd.InProgress() {
		// Wait for the next response (no timeout)
		c.Recv(-1)

		// Process command data
		for _, rsp = range cmd.Data {
			header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
			if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
				fmt.Println("|--", msg.Header.Get("Subject"))
			}
		}
		cmd.Data = nil

		// Process unilateral server data
		for _, rsp = range c.Data {
			fmt.Println("Server data:", rsp)
		}
		c.Data = nil
	}

	// Check command completion status
	if rsp, err := cmd.Result(imap.OK); err != nil {
		if err == imap.ErrAborted {
			fmt.Println("Fetch command aborted")
		} else {
			fmt.Println("Fetch error:", rsp.Info)
		}
	}
}