Files
sftpgo/internal/smtp/smtp.go
Nicola Murino f2618e7de6 switch from go-simple-mail to go-mail
Signed-off-by: Nicola Murino <nicola.murino@gmail.com>
2023-01-15 15:28:31 +01:00

225 lines
7.1 KiB
Go

// Copyright (C) 2019-2023 Nicola Murino
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// Package smtp provides supports for sending emails
package smtp
import (
"bytes"
"context"
"errors"
"fmt"
"html/template"
"path/filepath"
"time"
"github.com/wneessen/go-mail"
"github.com/drakkan/sftpgo/v2/internal/logger"
"github.com/drakkan/sftpgo/v2/internal/util"
)
const (
logSender = "smtp"
)
// EmailContentType defines the support content types for email body
type EmailContentType int
// Supported email body content type
const (
EmailContentTypeTextPlain EmailContentType = iota
EmailContentTypeTextHTML
)
const (
templateEmailDir = "email"
templatePasswordReset = "reset-password.html"
templatePasswordExpiration = "password-expiration.html"
)
var (
config *Config
emailTemplates = make(map[string]*template.Template)
)
// IsEnabled returns true if an SMTP server is configured
func IsEnabled() bool {
return config != nil
}
// Config defines the SMTP configuration to use to send emails
type Config struct {
// Location of SMTP email server. Leavy empty to disable email sending capabilities
Host string `json:"host" mapstructure:"host"`
// Port of SMTP email server
Port int `json:"port" mapstructure:"port"`
// From address, for example "SFTPGo <sftpgo@example.com>".
// Many SMTP servers reject emails without a `From` header so, if not set,
// SFTPGo will try to use the username as fallback, this may or may not be appropriate
From string `json:"from" mapstructure:"from"`
// SMTP username
User string `json:"user" mapstructure:"user"`
// SMTP password. Leaving both username and password empty the SMTP authentication
// will be disabled
Password string `json:"password" mapstructure:"password"`
// 0 Plain
// 1 Login
// 2 CRAM-MD5
AuthType int `json:"auth_type" mapstructure:"auth_type"`
// 0 no encryption
// 1 TLS
// 2 start TLS
Encryption int `json:"encryption" mapstructure:"encryption"`
// Domain to use for HELO command, if empty localhost will be used
Domain string `json:"domain" mapstructure:"domain"`
// Path to the email templates. This can be an absolute path or a path relative to the config dir.
// Templates are searched within a subdirectory named "email" in the specified path
TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
}
// Initialize initialized and validates the SMTP configuration
func (c *Config) Initialize(configDir string) error {
config = nil
if c.Host == "" {
logger.Debug(logSender, "", "configuration disabled, email capabilities will not be available")
return nil
}
if c.Port <= 0 || c.Port > 65535 {
return fmt.Errorf("smtp: invalid port %v", c.Port)
}
if c.AuthType < 0 || c.AuthType > 2 {
return fmt.Errorf("smtp: invalid auth type %v", c.AuthType)
}
if c.Encryption < 0 || c.Encryption > 2 {
return fmt.Errorf("smtp: invalid encryption %v", c.Encryption)
}
if c.From == "" && c.User == "" {
return fmt.Errorf(`smtp: from address and user cannot both be empty`)
}
templatesPath := util.FindSharedDataPath(c.TemplatesPath, configDir)
if templatesPath == "" {
return fmt.Errorf("smtp: invalid templates path %#v", templatesPath)
}
loadTemplates(filepath.Join(templatesPath, templateEmailDir))
config = c
logger.Debug(logSender, "", "configuration successfully initialized, host: %q, port: %d, username: %q, auth: %d, encryption: %d, helo: %q",
config.Host, config.Port, config.User, config.AuthType, config.Encryption, config.Domain)
return nil
}
func (c *Config) getMailClientOptions() []mail.Option {
options := []mail.Option{mail.WithPort(c.Port)}
switch c.Encryption {
case 1:
options = append(options, mail.WithSSL())
case 2:
options = append(options, mail.WithTLSPolicy(mail.TLSMandatory))
default:
options = append(options, mail.WithTLSPolicy(mail.NoTLS))
}
if config.User != "" {
options = append(options, mail.WithUsername(config.User))
}
if config.Password != "" {
options = append(options, mail.WithPassword(config.Password))
}
if config.User != "" || config.Password != "" {
switch config.AuthType {
case 1:
options = append(options, mail.WithSMTPAuth(mail.SMTPAuthLogin))
case 2:
options = append(options, mail.WithSMTPAuth(mail.SMTPAuthCramMD5))
default:
options = append(options, mail.WithSMTPAuth(mail.SMTPAuthPlain))
}
}
if config.Domain != "" {
options = append(options, mail.WithHELO(config.Domain))
}
return options
}
func loadTemplates(templatesPath string) {
logger.Debug(logSender, "", "loading templates from %#v", templatesPath)
passwordResetPath := filepath.Join(templatesPath, templatePasswordReset)
pwdResetTmpl := util.LoadTemplate(nil, passwordResetPath)
passwordExpirationPath := filepath.Join(templatesPath, templatePasswordExpiration)
pwdExpirationTmpl := util.LoadTemplate(nil, passwordExpirationPath)
emailTemplates[templatePasswordReset] = pwdResetTmpl
emailTemplates[templatePasswordExpiration] = pwdExpirationTmpl
}
// RenderPasswordResetTemplate executes the password reset template
func RenderPasswordResetTemplate(buf *bytes.Buffer, data any) error {
if !IsEnabled() {
return errors.New("smtp: not configured")
}
return emailTemplates[templatePasswordReset].Execute(buf, data)
}
// RenderPasswordExpirationTemplate executes the password expiration template
func RenderPasswordExpirationTemplate(buf *bytes.Buffer, data any) error {
if !IsEnabled() {
return errors.New("smtp: not configured")
}
return emailTemplates[templatePasswordExpiration].Execute(buf, data)
}
// SendEmail tries to send an email using the specified parameters.
func SendEmail(to []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
if !IsEnabled() {
return errors.New("smtp: not configured")
}
m := mail.NewMsg()
var from string
if config.From != "" {
from = config.From
} else {
from = config.User
}
if err := m.From(from); err != nil {
return fmt.Errorf("invalid from address: %w", err)
}
if err := m.To(to...); err != nil {
return err
}
m.Subject(subject)
m.SetDate()
m.SetMessageID()
m.SetAttachements(attachments)
switch contentType {
case EmailContentTypeTextPlain:
m.SetBodyString(mail.TypeTextPlain, body)
case EmailContentTypeTextHTML:
m.SetBodyString(mail.TypeTextHTML, body)
default:
return fmt.Errorf("smtp: unsupported body content type %v", contentType)
}
c, err := mail.NewClient(config.Host, config.getMailClientOptions()...)
if err != nil {
return fmt.Errorf("unable to create mail client: %w", err)
}
ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelFn()
return c.DialAndSendWithContext(ctx, m)
}