60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
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
|
|
}
|