all repos — navani @ 8836f20495e17361d15b1da6eb7bc4c6f2cd063c

forlater's primary mail processing service

mail/send.go (view raw)

 1package mail
 2
 3import (
 4	"fmt"
 5	"log"
 6	"os"
 7
 8	"git.icyphox.sh/forlater/navani/reader"
 9	"github.com/joegrasse/mail"
10	"github.com/joho/godotenv"
11)
12
13func init() {
14	err := godotenv.Load()
15	if err != nil {
16		log.Fatal("error loading .env file")
17	}
18}
19
20func SendArticle(article *reader.Article, to string, readable bool) error {
21	var (
22		EMAIL_USER_SECRET = os.Getenv("EMAIL_USER_SECRET")
23		EMAIL_PASSWORD    = os.Getenv("EMAIL_PASSWORD")
24		EMAIL_FROM        = os.Getenv("EMAIL_FROM")
25		SMTP_HOST         = os.Getenv("SMTP_HOST")
26		SMTP_PORT         = os.Getenv("SMTP_PORT")
27	)
28
29	htmlContent, err := RenderTemplate("html.tpl", article)
30	if err != nil {
31		return err
32	}
33
34	plainContent, err := reader.MakePlaintext(htmlContent)
35
36	email := mail.New()
37	email.Encryption = mail.EncryptionTLS
38	email.SetFrom(fmt.Sprintf("saved forlater <%s>", EMAIL_FROM))
39	email.AddTo(to)
40	if readable {
41		email.SetSubject(article.Title)
42		email.SetBody("text/plain", string(plainContent))
43		email.AddAlternative("text/html", string(htmlContent))
44	} else {
45		email.SetSubject(article.URL.String())
46		email.SetBody("text/plain", fmt.Sprintf(
47			"We were unable to parse your link: %s",
48			article.URL.String(),
49		))
50	}
51	email.Username = EMAIL_USER_SECRET
52	email.Password = EMAIL_PASSWORD
53
54	err = email.Send(SMTP_HOST + ":" + SMTP_PORT)
55	if err != nil {
56		return err
57	}
58
59	return nil
60}