all repos — navani @ 3d8e721aa152691f68eeeb75ae9bd23dab55b1ba

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	if err != nil {
36		return fmt.Errorf("making plaintext: %w\n", err)
37	}
38
39	email := mail.New()
40	email.Encryption = mail.EncryptionTLS
41	email.SetFrom(fmt.Sprintf("saved forlater <%s>", EMAIL_FROM))
42	email.AddTo(to)
43	if readable {
44		email.SetSubject(article.Title)
45		email.SetBody("text/plain", string(plainContent))
46		email.AddAlternative("text/html", string(htmlContent))
47	} else {
48		email.SetSubject(article.URL.String())
49		email.SetBody("text/plain", fmt.Sprintf(
50			"We were unable to parse your link: %s",
51			article.URL.String(),
52		))
53	}
54	email.Username = EMAIL_USER_SECRET
55	email.Password = EMAIL_PASSWORD
56
57	err = email.Send(SMTP_HOST + ":" + SMTP_PORT)
58	if err != nil {
59		return err
60	}
61	return nil
62}