github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/emailer/service.go (about) 1 package emailer 2 3 import ( 4 "github.com/cozy/cozy-stack/model/instance" 5 "github.com/cozy/cozy-stack/model/job" 6 "github.com/cozy/cozy-stack/pkg/mail" 7 ) 8 9 // EmailerService allows to send emails. 10 // 11 // This broker send the emails via anrasynchronous job. 12 type EmailerService struct { 13 jobBroker job.Broker 14 } 15 16 // NewEmailerService instantiates an [EmailerService]. 17 func NewEmailerService(jobBroker job.Broker) *EmailerService { 18 return &EmailerService{jobBroker} 19 } 20 21 // TransactionalEmailCmd contains the information to send a transactional email 22 // to the instance owner. 23 type TransactionalEmailCmd struct { 24 TemplateName string 25 TemplateValues map[string]interface{} 26 } 27 28 // SendEmail sends a mail to the instance owner. 29 func (s *EmailerService) SendEmail(inst *instance.Instance, cmd *TransactionalEmailCmd) error { 30 if cmd.TemplateName == "" || cmd.TemplateValues == nil { 31 return ErrMissingTemplate 32 } 33 34 msg, err := job.NewMessage(map[string]interface{}{ 35 "mode": "noreply", 36 "template_name": cmd.TemplateName, 37 "template_values": cmd.TemplateValues, 38 }) 39 if err != nil { 40 return err 41 } 42 43 _, err = s.jobBroker.PushJob(inst, &job.JobRequest{ 44 WorkerType: "sendmail", 45 Message: msg, 46 }) 47 48 return err 49 } 50 51 // SendPendingEmail sends a mail to the instance owner on their new pending 52 // email address. It is used to confirm that they can receive emails on the new 53 // email address. 54 func (s *EmailerService) SendPendingEmail(inst *instance.Instance, cmd *TransactionalEmailCmd) error { 55 if cmd.TemplateName == "" || cmd.TemplateValues == nil { 56 return ErrMissingTemplate 57 } 58 59 msg, err := job.NewMessage(map[string]interface{}{ 60 "mode": "pending", 61 "template_name": cmd.TemplateName, 62 "template_values": cmd.TemplateValues, 63 }) 64 if err != nil { 65 return err 66 } 67 68 _, err = s.jobBroker.PushJob(inst, &job.JobRequest{ 69 WorkerType: "sendmail", 70 Message: msg, 71 }) 72 73 return err 74 } 75 76 // CampaignEmailCmd contains the information required to send a campaign email 77 // to the instance owner. 78 type CampaignEmailCmd struct { 79 Parts []mail.Part 80 Subject string 81 } 82 83 // SendCampaignEmail sends a campaign email to the instance owner with the 84 // given cmd content via the dedicated campaign mail server. 85 func (s *EmailerService) SendCampaignEmail(inst *instance.Instance, cmd *CampaignEmailCmd) error { 86 if cmd.Subject == "" { 87 return ErrMissingSubject 88 } 89 if cmd.Parts == nil { 90 return ErrMissingContent 91 } 92 93 msg, err := job.NewMessage(map[string]interface{}{ 94 "mode": mail.ModeCampaign, 95 "subject": cmd.Subject, 96 "parts": cmd.Parts, 97 }) 98 if err != nil { 99 return err 100 } 101 102 _, err = s.jobBroker.PushJob(inst, &job.JobRequest{ 103 WorkerType: "sendmail", 104 Message: msg, 105 }) 106 107 return err 108 }