~gjabell/mfn

ref: 0.1.0 mfn/email.go -rw-r--r-- 1.5 KiB View raw
d0ec1c94Galen Abell Update README 2 months 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
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"
	"html/template"
	"net/mail"
	"strings"

	"github.com/emersion/go-sasl"
	"github.com/emersion/go-smtp"
	mf "miniflux.app/client"
)

type Email struct {
	subjectTemplate *template.Template
	bodyTemplate    *template.Template
	emailTo         string
	emailFrom       string
	username        string
	password        string
	server          string
}

func NewEmail(conf *Config) *Email {
	ec := conf.EmailConfig

	return &Email{
		subjectTemplate: ec.SubjectTemplate,
		bodyTemplate:    ec.BodyTemplate,
		emailTo:         ec.EmailTo,
		emailFrom:       ec.EmailFrom,
		username:        ec.Username,
		password:        ec.Password,
		server:          ec.Server,
	}
}

func (e *Email) Notify(entry *mf.Entry) error {
	var subject, body bytes.Buffer
	if err := e.subjectTemplate.Execute(&subject, entry); err != nil {
		return err
	}

	if err := e.bodyTemplate.Execute(&body, entry); err != nil {
		return err
	}

	auth := sasl.NewPlainClient("", e.username, e.password)

	toAddr, err := mail.ParseAddress(e.emailTo)
	if err != nil {
		return err
	}
	to := []string{toAddr.Address}

	fromAddr, err := mail.ParseAddress(e.emailFrom)
	if err != nil {
		return err
	}
	from := fromAddr.Address

	msg := strings.NewReader("To: " + e.emailTo + "\r\n" +
		"From: " + e.emailFrom + "\r\n" +
		"Subject: " + subject.String() + "\r\n" +
		"\r\n" +
		body.String() + "\r\n")
	if err := smtp.SendMail(e.server, auth, from, to, msg); err != nil {
		return err
	}

	return nil
}