all repos — navani @ b9e318987ea1da4422e9d5e1ce0bf72ee361a93d

forlater's primary mail processing service

mail/send.go (view raw)

 1package mail
 2
 3import (
 4	"fmt"
 5	"io"
 6	"log"
 7	"mime"
 8	"os"
 9
10	"git.icyphox.sh/forlater/navani/reader"
11	"git.icyphox.sh/rel2abs"
12	"github.com/joho/godotenv"
13	mail "github.com/xhit/go-simple-mail/v2"
14)
15
16func init() {
17	err := godotenv.Load()
18	if err != nil {
19		log.Fatal("error loading .env file")
20	}
21}
22
23func SendArticle(article *reader.Article, to string, readable bool) error {
24	var EMAIL_FROM = os.Getenv("EMAIL_FROM")
25	htmlContent, err := RenderTemplate("html.tpl", article)
26	if err != nil {
27		return err
28	}
29
30	htmlAbs, err := rel2abs.Convert(htmlContent, article.URL.String())
31	if err != nil {
32		htmlAbs = htmlContent
33	}
34
35	plainContent, err := reader.MakePlaintext(htmlAbs)
36	if err != nil {
37		return fmt.Errorf("making plaintext: %w\n", err)
38	}
39
40	email := mail.NewMSG()
41	email.SetFrom(fmt.Sprintf("saved forlater <%s>", EMAIL_FROM))
42	email.AddTo(to)
43	if readable {
44		email.SetSubject(article.Title)
45		email.SetBodyData(mail.TextPlain, plainContent)
46		email.AddAlternative(mail.TextHTML, string(htmlContent))
47	} else {
48		email.SetSubject("[forlater.email] Unable to read your link")
49		email.SetBody(mail.TextPlain, fmt.Sprintf(
50			"We were unable to parse your link: %s",
51			article.URL.String(),
52		))
53	}
54
55	c, err := mailClient()
56	if err != nil {
57		return fmt.Errorf("mail: %w\n", err)
58	}
59	err = email.Send(c)
60	if err != nil {
61		return err
62	}
63	return nil
64}
65
66func SendAttachment(r reader.Response, to string, url string) error {
67	var EMAIL_FROM = os.Getenv("EMAIL_FROM")
68	email := mail.NewMSG()
69	email.SetFrom(fmt.Sprintf("saved forlater <%s>", EMAIL_FROM))
70	email.AddTo(to)
71
72	b, err := io.ReadAll(r.Body)
73	if err != nil {
74		return fmt.Errorf("read attachment: %w\n", err)
75	}
76	fmt.Println(len(b))
77
78	ext, _ := mime.ExtensionsByType(r.MIMEType)
79	var name string
80	if ext != nil {
81		name = "file" + ext[0]
82	} else {
83		name = "file"
84	}
85	email.SetSubject(url)
86	email.Attach(&mail.File{MimeType: r.MIMEType, Data: b, Name: name, Inline: true})
87	email.SetBody(mail.TextPlain, fmt.Sprintf(`That didn't look like a HTML page; we found %s.
88We've attached it to this email.`, r.MIMEType))
89
90	c, err := mailClient()
91	if err != nil {
92		return fmt.Errorf("mail: %w\n", err)
93	}
94	err = email.Send(c)
95	if err != nil {
96		return err
97	}
98	return nil
99}