Skip to content

Instantly share code, notes, and snippets.

@immannino
Last active February 26, 2023 08:52
Show Gist options
  • Save immannino/56ccf06ec787be8aece85a4fbc0ab92e to your computer and use it in GitHub Desktop.
Save immannino/56ccf06ec787be8aece85a4fbc0ab92e to your computer and use it in GitHub Desktop.
// a small exmaple cli application for sending emails
//
// Expects a .env with the following configuration:
//
// EMAIL_ADDRESS=<from address>
// EMAIL_PASSWORD=<app password>
// EMAIL_HOST=smtp.gmail.com
// EMAIL_PORT=587
// RECIPIENT=<optional>
//
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/smtp"
"os"
"github.com/disgoorg/log"
"github.com/joho/godotenv"
"github.com/jordan-wright/email"
"github.com/spf13/cobra"
)
var (
recipient = ""
rootCmd = &cobra.Command{
Use: "email",
Short: "send an email with go",
Run: sendEmail,
}
)
func main() {
err := godotenv.Load(".env")
if err != nil {
log.Fatal(err)
}
rootCmd.Flags().StringVarP(&recipient, "recipient", "r", "", "The email recipient")
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func sendEmail(cmd *cobra.Command, args []string) {
if recipient == "" {
recipient = os.Getenv("RECIPIENT")
}
if recipient == "" {
log.Fatalf("no email recipient provided.\n%s", cmd.Usage())
}
contents, err := fetchHTML("https://text.npr.org")
if err != nil {
log.Fatal(err)
}
tmp, err := ioutil.TempFile("./", "attachment.*.html")
if err != nil {
log.Fatal(err)
}
_, err = tmp.Write([]byte(contents))
if err != nil {
log.Fatal(err)
}
defer tmp.Close()
defer os.RemoveAll(tmp.Name())
if err := sendWithAttachment(recipient, "attachment.html", contents, tmp.Name()); err != nil {
log.Error(err)
} else {
log.Info("✧˖°. test email sent ✧˖°.")
}
}
func sendWithAttachment(to, subject, body, attachmentFile string) error {
e := email.NewEmail()
e.From = fmt.Sprintf("<%s>", os.Getenv("EMAIL_ADDRESS"))
e.To = []string{os.Getenv("RECIPIENT")}
e.Subject = subject
e.HTML = []byte(body)
_, err := e.AttachFile(attachmentFile)
if err != nil {
return err
}
return e.Send(fmt.Sprintf("%s:%s", os.Getenv("EMAIL_HOST"), os.Getenv("EMAIL_PORT")), smtp.PlainAuth("", os.Getenv("EMAIL_ADDRESS"), os.Getenv("EMAIL_PASSWORD"), os.Getenv("EMAIL_HOST")))
}
func fetchHTML(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
if resp.StatusCode > http.StatusUnsupportedMediaType {
return "", errors.New("non successful response from server")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment