|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "html" |
| 8 | + "html/template" |
| 9 | + "io/ioutil" |
| 10 | + "log" |
| 11 | + "os" |
| 12 | + |
| 13 | + "github.com/yuin/goldmark" |
| 14 | + meta "github.com/yuin/goldmark-meta" |
| 15 | + "github.com/yuin/goldmark/parser" |
| 16 | + "gopkg.in/gomail.v2" |
| 17 | +) |
| 18 | + |
| 19 | +type subscriberList struct { |
| 20 | + Subscribers []string `json:"subscribers"` |
| 21 | +} |
| 22 | + |
| 23 | +func main() { |
| 24 | + markdown := goldmark.New( |
| 25 | + goldmark.WithExtensions( |
| 26 | + meta.Meta, |
| 27 | + ), |
| 28 | + ) |
| 29 | + |
| 30 | + jsonFile, err := os.Open("emails.json") |
| 31 | + |
| 32 | + if err != nil { |
| 33 | + log.Print(err) |
| 34 | + } |
| 35 | + |
| 36 | + defer jsonFile.Close() |
| 37 | + |
| 38 | + byteValue, _ := ioutil.ReadAll(jsonFile) |
| 39 | + |
| 40 | + var list subscriberList |
| 41 | + |
| 42 | + json.Unmarshal(byteValue, &list) |
| 43 | + |
| 44 | + content, _ := ioutil.ReadFile("../../content/post/example.md") |
| 45 | + |
| 46 | + var buf bytes.Buffer |
| 47 | + context := parser.NewContext() |
| 48 | + if err := markdown.Convert(content, &buf, parser.WithContext(context)); err != nil { |
| 49 | + panic(err) |
| 50 | + } |
| 51 | + metaData := meta.Get(context) |
| 52 | + title := metaData["title"] |
| 53 | + str := fmt.Sprintf("%v", title) |
| 54 | + |
| 55 | + t := template.New("template.html") |
| 56 | + t, _ = t.ParseFiles("template.html") |
| 57 | + |
| 58 | + var body bytes.Buffer |
| 59 | + |
| 60 | + if err := t.Execute(&body, struct { |
| 61 | + Content string |
| 62 | + Title string |
| 63 | + }{ |
| 64 | + Content: buf.String(), |
| 65 | + Title: str, |
| 66 | + }); err != nil { |
| 67 | + log.Println(err) |
| 68 | + } |
| 69 | + html := html.UnescapeString(body.String()) |
| 70 | + |
| 71 | + send(html, list.Subscribers) |
| 72 | +} |
| 73 | + |
| 74 | +func send(body string, to []string) { |
| 75 | + from := os.Getenv("MAIL_ID") |
| 76 | + pass := os.Getenv("MAIL_PASSWORD") |
| 77 | + |
| 78 | + d := gomail.NewDialer("smtp.gmail.com", 587, from, pass) |
| 79 | + s, err := d.Dial() |
| 80 | + if err != nil { |
| 81 | + panic(err) |
| 82 | + } |
| 83 | + |
| 84 | + bodyContent, err := ioutil.ReadFile("email_body.html") |
| 85 | + if err != nil { |
| 86 | + log.Fatal(err) |
| 87 | + } |
| 88 | + |
| 89 | + m := gomail.NewMessage() |
| 90 | + for _, r := range to { |
| 91 | + fmt.Printf("Sending email to: %s\n", r) |
| 92 | + m.SetHeader("From", from) |
| 93 | + m.SetAddressHeader("To", r, r) |
| 94 | + m.SetHeader("Subject", "OSDHACK '24 Attendance QR") |
| 95 | + m.SetBody("text/html", string(bodyContent)) |
| 96 | + |
| 97 | + if err := gomail.Send(s, m); err != nil { |
| 98 | + log.Printf("Could not send email to %q: %v", r, err) |
| 99 | + } |
| 100 | + m.Reset() |
| 101 | + } |
| 102 | +} |
0 commit comments