summaryrefslogtreecommitdiff
path: root/mailing.go
blob: a70138eeff4cbd9d2c5bc930d33cd329f86eb03a (plain)
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
package main

import (
	"kch42.de/gostuff/mailremind/mailing"
	"log"
)

var MailFrom string

type email struct {
	To, From string
	Msg      []byte
	OK       chan<- bool
}

var mailchan chan *email

func Mail(to, from string, msg []byte) bool {
	ok := make(chan bool)
	mailchan <- &email{to, from, msg, ok}
	return <-ok
}

func initMailing() {
	meth, err := conf.GetString("mail", "method")
	if err != nil {
		log.Fatalf("Could not get mail.method from config: %s", err)
	}

	MailFrom, err = conf.GetString("mail", "addr")
	if err != nil {
		log.Fatalf("Could not get mail.addr from config: %s", err)
	}

	parallel, err := conf.GetInt("mail", "parallel")
	if err != nil {
		log.Fatalf("Could not get mail.parallel from config: %s", err)
	}

	if parallel <= 0 {
		log.Fatalln("mail.parallel must be > 0")
	}

	mailchan = make(chan *email)

	mc, ok := mailing.MailersByName[meth]
	if !ok {
		log.Fatalf("Unknown mail method: %s", meth)
	}

	for i := int64(0); i < parallel; i++ {
		mailer, err := mc(conf)
		if err != nil {
			log.Fatalf("Error while initializing mail: %s", err)
		}

		go func(mailer mailing.Mailer) {
			for {
				mail := <-mailchan
				if err := mailer.Mail(mail.To, mail.From, mail.Msg); err != nil {
					log.Printf("Could not send mail to \"%s\": %s", mail.To, err)
					mail.OK <- false
				} else {
					mail.OK <- true
				}
			}
		}(mailer)
	}
}