~bigbes/core-go

ref: 0abb9c6b084e83f09b1b53bf71e01a242c1194be core-go/email/send.go -rw-r--r-- 1.1 KiB
0abb9c6b — Drew DeVault valid: Fix Sprintf call 4 years ago
                                                                                
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 (
	"context"
	"fmt"
	"io"
	"net/mail"
	"strconv"

	"github.com/emersion/go-sasl"
	"github.com/emersion/go-smtp"
	_ "github.com/emersion/go-message/charset"

	"git.sr.ht/~sircmpwn/core-go/config"
)

// Sends an email. Blocks until it's sent or an error occurs.
func Send(ctx context.Context, msg io.Reader, rcpts []string) error {
	conf := config.ForContext(ctx)

	portStr, ok := conf.Get("mail", "smtp-port")
	if !ok {
		panic(fmt.Errorf("[mail]smtp-port unset"))
	}
	port, err := strconv.Atoi(portStr)
	if err != nil {
		panic(fmt.Errorf("Unable to parse [mail]smtp-port (must be integer)"))
	}

	host, ok1 := conf.Get("mail", "smtp-host")
	user, ok2 := conf.Get("mail", "smtp-user")
	pass, ok3 := conf.Get("mail", "smtp-password")
	from, ok4 := conf.Get("mail", "smtp-from")
	if !ok1 || !ok2 || !ok3 || !ok4 {
		panic(fmt.Errorf("Missing SMTP configuration options"))
	}

	sender, err := mail.ParseAddress(from)
	if err != nil {
		panic(err)
	}

	auth := sasl.NewPlainClient("", user, pass)
	return smtp.SendMail(fmt.Sprintf("%s:%d", host, port),
		auth, sender.Address, rcpts, msg)
}