2021-12-19 13:22:55 -08:00
|
|
|
package services
|
|
|
|
|
|
|
|
import (
|
2021-12-19 17:37:51 -08:00
|
|
|
"fmt"
|
|
|
|
|
2021-12-19 13:22:55 -08:00
|
|
|
"goweb/config"
|
|
|
|
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
)
|
|
|
|
|
|
|
|
// MailClient provides a client for sending email
|
|
|
|
// This is purposely not completed because there are many different methods and services
|
|
|
|
// for sending email, many of which are very different. Choose what works best for you
|
|
|
|
// and populate the methods below
|
|
|
|
type MailClient struct {
|
|
|
|
// config stores application configuration
|
|
|
|
config *config.Config
|
2021-12-19 17:37:51 -08:00
|
|
|
|
|
|
|
templates *TemplateRenderer
|
2021-12-19 13:22:55 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewMailClient creates a new MailClient
|
2021-12-19 17:37:51 -08:00
|
|
|
func NewMailClient(cfg *config.Config, templates *TemplateRenderer) (*MailClient, error) {
|
2021-12-19 13:22:55 -08:00
|
|
|
return &MailClient{
|
2021-12-19 17:37:51 -08:00
|
|
|
config: cfg,
|
|
|
|
templates: templates,
|
2021-12-19 13:22:55 -08:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send sends an email to a given email address with a given body
|
|
|
|
func (c *MailClient) Send(ctx echo.Context, to, body string) error {
|
|
|
|
if c.skipSend() {
|
|
|
|
ctx.Logger().Debugf("skipping email sent to: %s")
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Finish based on your mail sender of choice
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SendTemplate sends an email to a given email address using a template and data which is passed to the template
|
|
|
|
// The template name should only include the filename without the extension or directory.
|
|
|
|
// The funcmap will be automatically added to the template and the data will be passed in.
|
|
|
|
func (c *MailClient) SendTemplate(ctx echo.Context, to, template string, data interface{}) error {
|
|
|
|
if c.skipSend() {
|
|
|
|
ctx.Logger().Debugf("skipping template email sent to: %s")
|
|
|
|
}
|
|
|
|
|
2021-12-19 17:37:51 -08:00
|
|
|
// Parse the template, if needed
|
|
|
|
if err := c.templates.Parse(
|
|
|
|
"mail",
|
|
|
|
template,
|
|
|
|
template,
|
|
|
|
[]string{fmt.Sprintf("email/%s", template)},
|
|
|
|
[]string{},
|
|
|
|
); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Execute the template
|
|
|
|
// Uncomment the first variable when ready to use
|
|
|
|
_, err := c.templates.Execute("mail", template, template, data)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-19 13:22:55 -08:00
|
|
|
// TODO: Finish based on your mail sender of choice
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// skipSend determines if mail sending should be skipped
|
|
|
|
func (c *MailClient) skipSend() bool {
|
|
|
|
return c.config.App.Environment != config.EnvProduction
|
|
|
|
}
|