areweplaying/pkg/email/config.go
Harry Culpan eb930b0794 Improve email config error to name the missing variable(s)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 20:37:39 -04:00

86 lines
1.7 KiB
Go

package email
import (
"fmt"
"os"
"strings"
"github.com/emersion/go-imap/client"
"github.com/joho/godotenv"
)
const (
IMAP_SERVICE EmailService = 993
SMTP_SERVICE EmailService = 587
)
type EmailService int
type Config struct {
Username string
Password string
ImapServer string
SmtpServer string
}
func NewConfig(username, password, imapServer, smtpServer string) *Config {
return &Config{
Username: username,
Password: password,
ImapServer: imapServer,
SmtpServer: smtpServer,
}
}
func NewConfigFromEnv() (*Config, error) {
var username string
var password string
var fetchServer string
var sendServer string
godotenv.Load()
username = os.Getenv("EMAIL_USERNAME")
password = os.Getenv("EMAIL_PASSWORD")
fetchServer = os.Getenv("IMAP_SERVER")
sendServer = os.Getenv("SMTP_SERVER")
var missing []string
if len(username) == 0 {
missing = append(missing, "EMAIL_USERNAME")
}
if len(password) == 0 {
missing = append(missing, "EMAIL_PASSWORD")
}
if len(fetchServer) == 0 {
missing = append(missing, "IMAP_SERVER")
}
if len(sendServer) == 0 {
missing = append(missing, "SMTP_SERVER")
}
if len(missing) > 0 {
return nil, fmt.Errorf("missing configuration variables: %s", strings.Join(missing, ", "))
}
return NewConfig(username, password, fetchServer, sendServer), nil
}
func (c *Config) ConnectToServer(service EmailService) (*client.Client, error) {
port := int(service)
var host string
if service == SMTP_SERVICE {
host = c.SmtpServer
} else {
host = c.ImapServer
}
client, err := client.DialTLS(fmt.Sprintf("%s:%d", host, port), nil)
if err != nil {
return nil, err
}
if err := client.Login(c.Username, c.Password); err != nil {
return nil, err
}
return client, nil
}