refactor, working prototype

This commit is contained in:
2023-04-08 02:31:59 +02:00
parent 9b614b549e
commit 214f9d8599
9 changed files with 282 additions and 162 deletions

View File

@@ -1,31 +1,27 @@
package cmd
import (
"fmt"
"log"
"github.com/spf13/cobra"
"git.dafu.dev/dafu/gomailer/pkg"
)
// inlineCmd represents the send command
var inlineCmd = &cobra.Command{
Use: "inline",
Short: "Inline styles in template without sending",
Long: ``,
Short: "Inline styles in template file without sending",
Long: `Inlines styles in given template and saves it to *_inlined.html`,
Args: cobra.MinimumNArgs(1),
Use: "inline [flags] [...template.html]",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("send called")
log.Printf("Templates: %v", args)
for _, arg := range args {
gomailer.Inline(arg)
}
},
}
func init() {
rootCmd.AddCommand(inlineCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// inlineCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// inlineCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

View File

@@ -1,22 +1,28 @@
package cmd
import (
"fmt"
"log"
"os"
"git.dafu.dev/dafu/gomailer/pkg"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var Cfg Config
type Config struct {
mailserver gomailer.MailServer `mapstructure:"mailserver"`
mailsettings gomailer.MailSettings `mapstructure:"mailsettings"`
}
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "gomailer",
Short: "use it to test email templates",
Long: ``,
// Uncomment the following line if your bare application
// has an action associated with it:
Long: ``,
// Run: func(cmd *cobra.Command, args []string) { },
}
@@ -31,38 +37,61 @@ func Execute() {
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gomailer.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
// rootCmd.PersistentFlags().StringVarP(&Template, "template", "t", "", "Path to html template")
// viper.BindPFlag("template", rootCmd.PersistentFlags().Lookup("template"))
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
// Search config in home directory with name ".gomailer" (without extension).
viper.AddConfigPath(home)
viper.AddConfigPath(".")
viper.SetConfigType("yaml")
viper.SetConfigName(".gomailer")
viper.SetConfigName("gomailer")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
mserver := &gomailer.MailServer{}
msettings := &gomailer.MailSettings{}
if err := viper.UnmarshalKey("mailserver", mserver); err != nil {
log.Fatal(err)
}
if err := viper.UnmarshalKey("mailsettings", msettings); err != nil {
log.Fatal(err)
}
Cfg.mailserver = *mserver
Cfg.mailsettings = *msettings
} else {
generateDefaultConfig()
}
}
func generateDefaultConfig() {
// mailserver
viper.SetDefault("mailserver.Port", 25)
viper.SetDefault("mailserver.Host", "localhost")
viper.SetDefault("mailserver.Username", "user")
viper.SetDefault("mailserver.Password", "pass")
viper.SetDefault("mailserver.Tls", "notls|mandatory")
viper.SetDefault("mailserver.Authtype", "nologin|plain|login|cram-md5")
viper.SetDefault("mailserver.Skipverify", false)
// mailsettings
viper.SetDefault("mailsettings.Subject", "subject")
viper.SetDefault("mailsettings.From", "from@local")
viper.SetDefault("mailsettings.To", "to@local")
viper.SetDefault("mailsettings.Cc", "cc@local")
viper.SetDefault("mailsettings.Template", "email.html")
viper.SetDefault("mailsettings.Inline", true)
viper.SafeWriteConfig()
log.Printf("Writing default config file: " + viper.ConfigFileUsed())
}

View File

@@ -1,20 +1,11 @@
package cmd
import (
ht "html/template"
"log"
"os"
"git.dafu.dev/dafu/gomailer/pkg"
"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",
@@ -24,71 +15,14 @@ var sendmailCmd = &cobra.Command{
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)
}
gomailer.SendMail(Cfg.mailsettings, Cfg.mailserver)
},
}
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")
// sendmailCmd.Flags().BoolVar(&help, "test", false, "Help message for sendmail")
// sendmailCmd.Flags().BoolVarP(&inline, "inline", "i", false, "Inline css")
}

View File

@@ -1,40 +0,0 @@
package cmd
import (
"log"
"strings"
"golang.org/x/net/html"
)
func findSrcInHtml(doc string) []string {
var results []string
reader := strings.NewReader(doc)
if document, err := html.Parse(reader); err == nil {
var parser func(*html.Node)
parser = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "img" {
var imgSrcUrl string
for _, element := range n.Attr {
if element.Key == "src" {
imgSrcUrl = element.Val
log.Print("found image:" + imgSrcUrl)
results = append(results, imgSrcUrl)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
parser(c)
}
}
parser(document)
} else {
log.Panicln("Parse html error", err)
}
return results
}