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