package cmd import ( ht "html/template" "log" "os" "github.com/spf13/cobra" "github.com/vanng822/go-premailer/premailer" "github.com/wneessen/go-mail" ) var help bool var inline bool var template string var output string // sendmailCmd represents the sendmail command var sendmailCmd = &cobra.Command{ Use: "sendmail", Short: "Send mail with the configured server", Long: `Send Emails for testing Mail templates: sendmail.`, Run: func(cmd *cobra.Command, args []string) { prem, err := premailer.NewPremailerFromFile(template, premailer.NewOptions()) if err != nil { log.Fatal(err) } html, err := prem.Transform() if err != nil { log.Fatal(err) } f, err := os.Create(template + "_inlined.html") defer f.Close() f.WriteString(html) f.Sync() // fmt.Println(html) m := mail.NewMsg() if err := m.From("sender@domain.local"); err != nil { log.Fatalf("failed to set From address: %s", err) } if err := m.To("recipient@domain.local"); err != nil { log.Fatalf("failed to set To address: %s", err) } m.Subject("Subject") htpl, err := ht.New("htmltpl").Parse(html) if err != nil { log.Fatalf("failed to parse text template: %s", err) } // embedd images for _, val := range findSrcInHtml(html) { log.Println("embedding: " + val) m.EmbedFile(val) } m.SetBodyHTMLTemplate(htpl, nil) c, err := mail.NewClient("localhost", mail.WithPort(25), mail.WithTLSPolicy(mail.NoTLS)) if err != nil { log.Fatalf("failed to create mail client: %s", err) } if err := c.DialAndSend(m); err != nil { log.Fatalf("failed to send mail: %s", err) } }, } func init() { rootCmd.AddCommand(sendmailCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // sendmailCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: sendmailCmd.Flags().BoolVar(&help, "test", false, "Help message for sendmail") sendmailCmd.Flags().BoolVarP(&inline, "inline", "i", false, "Inline css") sendmailCmd.Flags().StringVarP(&template, "template", "t", "", "Path to html template") sendmailCmd.Flags().StringVarP(&output, "output", "o", "", "Path to save inlined html") }