63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package mail
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
var validate *validator.Validate
|
|
|
|
type Email struct {
|
|
Path string
|
|
Sender string `json:"sender" validate:"required,email"`
|
|
Receivers string `json:"receivers" validate:"required"`
|
|
Subject string `json:"subject" validate:"required"`
|
|
Content string `json:"content" validate:"required"`
|
|
}
|
|
|
|
func FromJSON(path string) (Email, error) {
|
|
var email Email
|
|
|
|
content, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return email, fmt.Errorf("%w, unable to read the file: %s", err, path)
|
|
}
|
|
|
|
if err := json.Unmarshal(content, &email); err != nil {
|
|
return email, err
|
|
}
|
|
|
|
if err := email.Validate(); err != nil {
|
|
return email, err
|
|
}
|
|
|
|
return email, nil
|
|
}
|
|
|
|
func (e *Email) GetReceivers() []string {
|
|
return strings.Split(e.Receivers, ",")
|
|
}
|
|
|
|
func (e *Email) Generate() []byte {
|
|
mail := fmt.Sprintf(
|
|
"To: %s\nFrom: %s\nContent-Type: text/html;charset=utf-8\nSubject: %s\n\n%s",
|
|
e.Receivers,
|
|
e.Sender,
|
|
e.Subject,
|
|
e.Content,
|
|
)
|
|
return []byte(mail)
|
|
}
|
|
|
|
func (e *Email) Validate() error {
|
|
validate = validator.New(validator.WithRequiredStructEnabled())
|
|
if err := validate.Struct(e); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|