Skip to content
impl_smtp.go 1.4 KiB
Newer Older
Lo^2's avatar
Lo^2 committed
package email

import (
	"code.electrolab.fr/it/vote.electrolab.fr/service"
	"fmt"
	"net/smtp"
	"strings"
)

type Smtp struct {
	disabled  bool
	address   string
	port      int
	fromEmail string
	auth      smtp.Auth
}

type SmtpConfig struct {
	Disabled  bool
	Address   string
	Port      int
	User      string
	Password  string
	FromEmail string
}

func NewSmtp(config SmtpConfig) *Smtp {
	s := &Smtp{
		disabled:  config.Disabled,
		address:   config.Address,
		port:      config.Port,
		fromEmail: config.FromEmail,
	}

	if len(config.User) > 0 {
		s.auth = smtp.PlainAuth("", config.User, config.Password, config.Address)
	}

	return s
}

func (s *Smtp) Name() string {
	return fmt.Sprintf("%T", s)[1:]
}

func (s *Smtp) Send(to string, subject, body string) error {
Lo^2's avatar
Lo^2 committed
	msg := fmt.Sprintf("From: %s\nTo: %s\nSubject: %s\nContent-Type:text/plain; charset=UTF-8\n\n%s\n", s.fromEmail, to, subject, body)
Lo^2's avatar
Lo^2 committed
	msg = strings.Replace(msg, "\n", "\r\n", -1)
	if !s.disabled {
		serverAddr := fmt.Sprintf("%s:%d", s.address, s.port)
		err := smtp.SendMail(serverAddr, nil, s.fromEmail, []string{to}, []byte(msg))
		if err != nil {
			return fmt.Errorf("SMTP error: %s", err.Error())
		}
	}
	return nil
}

func (s *Smtp) Start() error {
	if s.port == 0 {
		return fmt.Errorf("Invalid smtp port")
	}
	return nil
}

func (s *Smtp) Stop() error                     { return nil }
func (s *Smtp) Dependencies() []service.Service { return nil }