"Life is all about sharing. If we are good at something, pass it on." - Mary Berry

Save draft mail in Zimbra web client using ChromeDP

visitor badge

2020-07-03

Categories: Programming

As an engineer, I want to automate everything as much as possible. This CLI tool is created to save a draft mail in Zimbra web client.

Read config file:

 1func initConfig() {
 2	if cfgFile != "" {
 3		// Use config file from the flag.
 4		viper.SetConfigFile(cfgFile)
 5	} else {
 6		// Find home directory.
 7		home, err := homedir.Dir()
 8		if err != nil {
 9			fmt.Println(err)
10			os.Exit(1)
11		}
12
13		// Search config in home directory with name ".zwc" (without extension).
14		viper.AddConfigPath(home)
15		viper.SetConfigName(".zwc")
16	}
17
18	viper.AutomaticEnv() // read in environment variables that match
19
20	// If a config file is found, read it in.
21	if err := viper.ReadInConfig(); err != nil {
22		log.Fatal(err)
23	}
24
25	fmt.Println("Using config file:", viper.ConfigFileUsed())
26}

Create a new chromedp context:

1		allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.Flag("headless", false))...)
2		defer cancel()
3
4		ctx, cancel := chromedp.NewContext(allocCtx, chromedp.WithDebugf(log.Printf))
5		defer cancel()

Get flag values:

1		subject, err := cmd.Flags().GetString("subject")
2		if err != nil {
3			log.Fatal(err)
4		}
5
6		attachFile, err := cmd.Flags().GetString("attach")
7		if err != nil {
8			log.Fatal(err)
9		}

And save draft mail:

 1func zwcSaveDraft(subject, attachFile string) chromedp.Tasks {
 2	selName := `//input[@id="username"]`
 3	selPass := `//input[@id="password"]`
 4
 5	return chromedp.Tasks{
 6		chromedp.Navigate(viper.GetString("url")),
 7		chromedp.WaitVisible(selPass),
 8		chromedp.SendKeys(selName, viper.GetString("username")),
 9		chromedp.SendKeys(selPass, viper.GetString("password")),
10		chromedp.Submit(selPass),
11		chromedp.WaitVisible(`//div[@id="z_userName"]`),
12		chromedp.Click(`//div[@title="Compose"]`),
13		chromedp.WaitVisible(`//div[@id="zb__App__tab_COMPOSE-1"]`),
14		chromedp.SendKeys(`//input[@id="zv__COMPOSE-1_subject_control"]`, subject),
15		chromedp.SendKeys(`//input[@type="file"]`, attachFile, chromedp.NodeVisible),
16		chromedp.WaitVisible(`//a[@class="AttLink"]`),
17		chromedp.Click(`//div[@id="zb__COMPOSE-1__SAVE_DRAFT"]`),
18	}
19}

GitHub repository: https://github.com/quantonganh/zwc

Tags: chromedp golang cobra

Edit on GitHub

Related Posts: