forked from itsabot/itsabot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emailsender.go
84 lines (74 loc) · 2.18 KB
/
emailsender.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Package emailsender enables Abot to send email through any external service.
// It implements a standardized interface through which Sendgrid and more can
// be supported. It's up to individual drivers to add support for each of these
// email sending services. To both send and receive emails, use interface/email
// instead.
package emailsender
import (
"fmt"
"sort"
"sync"
"github.com/itsabot/abot/shared/interface/emailsender/driver"
)
var driversMu sync.RWMutex
var drivers = make(map[string]driver.Driver)
// Register makes a email driver available by the provided name. If Register
// is called twice with the same name or if driver is nill, it panics.
func Register(name string, driver driver.Driver) {
driversMu.Lock()
defer driversMu.Unlock()
if driver == nil {
panic("cal: Register driver is nil")
}
if _, dup := drivers[name]; dup {
panic("cal: Register called twice for driver " + name)
}
drivers[name] = driver
}
// Drivers returns a sorted list of the names of the registered drivers.
func Drivers() []string {
driversMu.RLock()
defer driversMu.RUnlock()
var list []string
for name := range drivers {
list = append(list, name)
}
sort.Strings(list)
return list
}
// Conn is a connection to a specific emailsender driver.
type Conn struct {
driver driver.Driver
conn driver.Conn
}
// Open a connection to a registered driver.
func Open(driverName, auth string) (*Conn, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
driversMu.RUnlock()
if !ok {
return nil, fmt.Errorf("sms: unknown driver %q (forgotten import?)",
driverName)
}
conn, err := driveri.Open(auth)
if err != nil {
return nil, err
}
c := &Conn{
driver: driveri,
conn: conn,
}
return c, nil
}
// SendHTML email through the opened driver connection.
func (c *Conn) SendHTML(to []string, from, subj, html string) error {
return c.conn.SendHTML(to, from, subj, html)
}
// SendPlainText email through the opened driver connection.
func (c *Conn) SendPlainText(to []string, from, subj, plaintext string) error {
return c.conn.SendPlainText(to, from, subj, plaintext)
}
// Driver returns the driver used by a connection.
func (c *Conn) Driver() driver.Driver {
return c.driver
}