Added imaputils module
This commit is contained in:
parent
5fb994bd68
commit
54a31ad825
2 changed files with 93 additions and 0 deletions
60
imaputils/connection.go
Normal file
60
imaputils/connection.go
Normal file
|
@ -0,0 +1,60 @@
|
|||
package imaputils
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.lattuga.net/blallo/papero/config"
|
||||
"github.com/emersion/go-imap/client"
|
||||
)
|
||||
|
||||
var ErrMissingConfig = errors.New("missing configuration stanza")
|
||||
var ErrUnencrypted = errors.New("the connection is unencrypted")
|
||||
|
||||
type IMAPConnection struct {
|
||||
config *config.AccountData
|
||||
client *client.Client
|
||||
}
|
||||
|
||||
func NewConnection(conf *config.AccountData) *IMAPConnection {
|
||||
conn := &IMAPConnection{}
|
||||
conn.config = conf
|
||||
return conn
|
||||
}
|
||||
|
||||
func (c *IMAPConnection) Start(debug bool) error {
|
||||
var err error
|
||||
c.client, err = tryConnection(c.config.Host, c.config.Port)
|
||||
if err != nil {
|
||||
// TODO: allow unencrypted connections
|
||||
return err
|
||||
}
|
||||
if debug {
|
||||
c.client.SetDebug(os.Stderr)
|
||||
}
|
||||
|
||||
return c.client.Login(c.config.Username, c.config.Password)
|
||||
}
|
||||
|
||||
func (c *IMAPConnection) Close() {
|
||||
c.client.Logout()
|
||||
}
|
||||
|
||||
func tryConnection(host string, port int) (*client.Client, error) {
|
||||
connString := fmt.Sprintf("%s:%d", host, port)
|
||||
c, err := client.DialTLS(connString, nil)
|
||||
if err == nil {
|
||||
return c, err
|
||||
}
|
||||
c, err = client.Dial(connString)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
err = c.StartTLS(&tls.Config{ServerName: host})
|
||||
if err != nil {
|
||||
err = ErrUnencrypted
|
||||
}
|
||||
return c, err
|
||||
}
|
33
imaputils/info.go
Normal file
33
imaputils/info.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
package imaputils
|
||||
|
||||
import (
|
||||
"git.lattuga.net/blallo/papero/config"
|
||||
"github.com/emersion/go-imap"
|
||||
)
|
||||
|
||||
func ListMailboxes(conf *config.AccountData, debug bool) ([]*imap.MailboxInfo, error) {
|
||||
var mailboxes []*imap.MailboxInfo
|
||||
conn := NewConnection(conf)
|
||||
|
||||
err := conn.Start(debug)
|
||||
if err != nil {
|
||||
return mailboxes, err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
mboxChan := make(chan *imap.MailboxInfo, 10)
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- conn.client.List("", "*", mboxChan)
|
||||
}()
|
||||
|
||||
for m := range mboxChan {
|
||||
mailboxes = append(mailboxes, m)
|
||||
}
|
||||
|
||||
if err := <-done; err != nil {
|
||||
return mailboxes, err
|
||||
}
|
||||
|
||||
return mailboxes, nil
|
||||
}
|
Loading…
Reference in a new issue