Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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 {
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)
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 }