summaryrefslogtreecommitdiff
path: root/mails.go
blob: 5fe663da183f6b20b5dcf7b0d66f31fe2c908be0 (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
70
71
72
package main

import (
	"bytes"
	"fmt"
	"github.com/kch42/mailremind/confhelper"
	"github.com/kch42/mailremind/model"
	"log"
	"path"
	"text/template"
	"time"
)

func loadMailTpl(tplroot, name string) *template.Template {
	tpl, err := template.ParseFiles(path.Join(tplroot, name+".tpl"))
	if err != nil {
		log.Fatalf("Could not load mailtemplate %s: %s", name, err)
	}
	return tpl
}

var (
	mailActivationcode *template.Template
	mailPwreset        *template.Template
)

func initMails() {
	tplroot := confhelper.ConfStringOrFatal(conf, "paths", "mailtpls")

	mailActivationcode = loadMailTpl(tplroot, "activationcode")
	mailPwreset = loadMailTpl(tplroot, "pwreset")
}

type activationcodeData struct {
	URL string
}

func SendActivationcode(to, acCode string, uid model.DBID) bool {
	buf := new(bytes.Buffer)
	fmt.Fprintf(buf, "To: %s\n", to)
	fmt.Fprintf(buf, "From: %s\n", MailFrom)
	fmt.Fprintf(buf, "Subject: Activation code for your mailremind account\n")
	fmt.Fprintf(buf, "Date: %s\n", time.Now().Format(time.RFC1123Z))

	fmt.Fprintln(buf, "")

	url := fmt.Sprintf("%s/activate?U=%s&Code=%s", baseurl, uid, acCode)
	if err := mailActivationcode.Execute(buf, activationcodeData{url}); err != nil {
		log.Printf("Error while executing mail template (activationcode): %s", err)
		return false
	}

	return Mail(to, MailFrom, buf.Bytes())
}

func SendPwresetLink(to, code string, uid model.DBID) bool {
	buf := new(bytes.Buffer)
	fmt.Fprintf(buf, "To: %s\n", to)
	fmt.Fprintf(buf, "From: %s\n", MailFrom)
	fmt.Fprintf(buf, "Subject: Password reset request for your mailremind account\n")
	fmt.Fprintf(buf, "Date: %s\n", time.Now().Format(time.RFC1123Z))

	fmt.Fprintln(buf, "")

	url := fmt.Sprintf("%s/pwreset?U=%s&Code=%s", baseurl, uid, code)
	if err := mailPwreset.Execute(buf, activationcodeData{url}); err != nil {
		log.Printf("Error while executing mail template (pwreset): %s", err)
		return false
	}

	return Mail(to, MailFrom, buf.Bytes())
}