/* * Hexacode Mailer * Package: gitlab.hexacode.org/go-libs/mailer * Maintainer: Azzis Arswendo * * Copyright (C) 2023 Hexacode Teknologi Indonesia * All Rights Reserved */ // Example: // // ```go // // package main // // import ( // // "gitlab.hexacode.org/go-libs/hctypes" // "gitlab.hexacode.org/go-libs/mailer" // // ) // // func main() { // // Create a new template // // Please see https://github.com/noirbizarre/gonja for more details template // tmpl, err := mailer.NewTemplate("Hello {{ name }}!") // if err != nil { // panic(err) // } // // // Create a new sender // sender := mailer.NewSender("Example Sender", "example-sender@gmail.com", "password", "smtp.gmail.com", 587, tmpl) // // // Send an email // err = sender.SendEmail("example-recipient@gmail.com", "Example Subject", hctypes.Dict{"name": "John Doe"}) // if err != nil { // panic(err) // } // } // // ``` package mailer import ( "fmt" "github.com/go-mail/mail" "gitlab.hexacode.org/go-libs/hctypes" ) // Sender represents a mail sender type Sender struct { sender_name string // The name of the sender sender_address string // The email address of the sender password string // The password of the sender smtp_host string // The smtp host (eg: smtp.gmail.com) smtp_port int // The smtp port (eg: 587) Template *Template // The template *Template } // NewSender creates a new Sender // // sender_name: The name of the sender // sender_address: The email address of the sender // password: The password of the sender // smtp_host: The smtp host (eg: smtp.gmail.com) // smtp_port: The smtp port (eg: 587) // template: The template *Template // Returns: *Sender func NewSender(sender_name, sender_address, password, smtp_host string, smtp_port int, template *Template) *Sender { return &Sender{ sender_name: sender_name, sender_address: sender_address, password: password, smtp_host: smtp_host, smtp_port: smtp_port, Template: template, } } // SendEmail sends an email // // to: The email address of the recipient // subject: The subject of the email // query: The query of the email template // Returns: error func (s *Sender) SendEmail(to, subject string, query hctypes.Dict) error { from := fmt.Sprintf("%s <%s>", s.sender_name, s.sender_address) msg := mail.NewMessage() msg.SetHeader("From", from) msg.SetHeader("To", to) msg.SetHeader("Subject", subject) body, err := s.Template.Render(query) if err != nil { return err } msg.SetBody("text/html", body) dial := mail.NewDialer(s.smtp_host, s.smtp_port, s.sender_address, s.password) return dial.DialAndSend(msg) }