Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion api-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,44 @@ API forwards this token to SMTP using XOAUTH2 and does not validate it locally.
| `app_name` | string | "Application" | Application name for email template |
| `template` | string | - | Custom email template |
| `template_data` | object | - | Data for custom template |
| `subject` | string | - | Subject, sent as written (see [Content as written](#content-as-written)) |
| `text_body` | string | - | Plain-text body, sent as written |
| `html_body` | string | - | HTML body, sent as written |

## Content as written

A caller that renders its own email sends `subject` with `text_body`,
`html_body` or both, and PingMailer sends them as they are: no template is
applied and nothing is escaped. At least one body is required, and these
fields can't be combined with `template` (400). With both bodies the email is
`multipart/alternative`; with one, it has that body alone.

```bash
curl -X POST http://your-host:8000/notify \
-H "Authorization: Bearer <access-token>" \
-H "Content-Type: application/json" \
-d '{
"smtp_host": "smtp-server",
"smtp_port": 587,
"smtp_username": "noreply@domain.com",
"smtp_sender": "noreply@domain.com",
"recipients": [{ "email": "user@example.com" }],
"subject": "Your application is under review",
"text_body": "Dear Tom & Jerry, your application is under review.",
"html_body": "<p>Dear Tom &amp; Jerry, your application is under review.</p>"
}'
```

## Custom Templates

You can use custom email templates by providing the `template` and `template_data` fields.

### Template Format

Templates use Go's `text/template` syntax with three parts:
Templates use Go's `html/template` syntax with three parts. Values from
`template_data` are HTML-escaped in all three, the subject and plain-text body
included, so a caller with content of its own sends it
[as written](#content-as-written) instead.

```go
{{define "subject"}}Your Subject Here{{end}}
Expand Down
27 changes: 27 additions & 0 deletions api-server/internal/api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ type notifyRequest struct {
AppName string `json:"app_name"`
Template string `json:"template,omitempty"` // Optional: custom template content
TemplateData map[string]any `json:"template_data,omitempty"` // Optional: custom template data
// Optional: the email's content as it is sent, with no template applied.
// Set instead of template; at least one of text_body and html_body is
// required with it.
Subject string `json:"subject,omitempty"`
TextBody string `json:"text_body,omitempty"`
HTMLBody string `json:"html_body,omitempty"`
}

// hasContent reports whether the request carries its content as written
// rather than through a template.
func (r notifyRequest) hasContent() bool {
return r.Subject != "" || r.TextBody != "" || r.HTMLBody != ""
}

func (app *App) handleNotify(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -126,6 +138,14 @@ func validateNotifyRequest(w http.ResponseWriter, req notifyRequest) bool {
return false
}

if req.hasContent() {
if !required(req.Template == "", "template cannot be combined with subject, text_body or html_body") {
return false
}
if !required(req.TextBody != "" || req.HTMLBody != "", "Missing required field: text_body or html_body") {
return false
}
}
if _, err := mail.ParseAddress(req.SMTPSender); err != nil {
http.Error(w, "Invalid smtp_sender email format: "+err.Error(), http.StatusBadRequest)
return false
Expand Down Expand Up @@ -192,6 +212,13 @@ func sendNotifyEmail(mailer emailer.Mailer, req notifyRequest, recipients []user
var sendErrors []error

for _, recipient := range recipients {
if req.hasContent() {
msg := emailer.Message{Subject: req.Subject, TextBody: req.TextBody, HTMLBody: req.HTMLBody}
if err := mailer.SendMessage(recipient.Email, msg); err != nil {
sendErrors = append(sendErrors, fmt.Errorf("recipient %s: %w", recipient.Email, err))
}
continue
}
if req.Template == "" {
if err := mailer.Send(recipient.Email, "welcome.tmpl", recipient); err != nil {
sendErrors = append(sendErrors, fmt.Errorf("recipient %s: %w", recipient.Email, err))
Expand Down
43 changes: 43 additions & 0 deletions api-server/internal/api/handlers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package api

import (
"net/http"
"net/http/httptest"
"testing"
)

func validRequest() notifyRequest {
return notifyRequest{
SMTPHost: "smtp.example.com",
SMTPPort: 587,
SMTPUsername: "no-reply@example.com",
SMTPSender: "no-reply@example.com",
Recipients: []recipient{{Email: "to@example.com"}},
}
}

// Content sent as written needs a body, and can't be combined with a template.
func TestValidateNotifyRequest_Content(t *testing.T) {
for name, tc := range map[string]struct {
edit func(*notifyRequest)
want int
}{
"template only": {func(r *notifyRequest) { r.Template = `{{define "subject"}}s{{end}}` }, http.StatusOK},
"text body": {func(r *notifyRequest) { r.Subject, r.TextBody = "s", "hello" }, http.StatusOK},
"html body": {func(r *notifyRequest) { r.Subject, r.HTMLBody = "s", "<p>hello</p>" }, http.StatusOK},
"subject only": {func(r *notifyRequest) { r.Subject = "s" }, http.StatusBadRequest},
"with a template": {func(r *notifyRequest) { r.TextBody, r.Template = "hello", "t" }, http.StatusBadRequest},
} {
t.Run(name, func(t *testing.T) {
req := validRequest()
tc.edit(&req)
w := httptest.NewRecorder()

ok := validateNotifyRequest(w, req)

if got := map[bool]int{true: http.StatusOK, false: w.Code}[ok]; got != tc.want {
t.Errorf("got %d, want %d (%s)", got, tc.want, w.Body.String())
}
})
}
}
75 changes: 51 additions & 24 deletions api-server/internal/emailer/emailer.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,43 +87,70 @@ func (m Mailer) SendWithCustomTemplate(recipient, templateContent string, data a
return m.send(recipient, tmpl, data)
}

// send is an internal method that handles the common email sending logic.
// It executes the template blocks and sends the email via SMTP.
func (m Mailer) send(recipient string, tmpl *template.Template, data any) error {
subject := new(bytes.Buffer)
err := tmpl.ExecuteTemplate(subject, "subject", data)
if err != nil {
return err
}
// Message is an email's content as it is sent: no template is applied to it.
// At least one of TextBody and HTMLBody is set.
type Message struct {
Subject string
TextBody string
HTMLBody string
}

plainBody := new(bytes.Buffer)
err = tmpl.ExecuteTemplate(plainBody, "plainBody", data)
if err != nil {
return err
// SendMessage delivers msg to the recipient as written. A message with both
// bodies is sent as multipart/alternative; one with a single body is sent with
// that body alone.
func (m Mailer) SendMessage(recipient string, msg Message) error {
if msg.TextBody == "" && msg.HTMLBody == "" {
return errors.New("message has no body")
}
return m.deliver(m.build(recipient, msg))
}

htmlBody := new(bytes.Buffer)
err = tmpl.ExecuteTemplate(htmlBody, "htmlBody", data)
if err != nil {
return err
// send renders the template's "subject", "plainBody" and "htmlBody" blocks
// with data and delivers the result.
func (m Mailer) send(recipient string, tmpl *template.Template, data any) error {
var msg Message
for _, block := range []struct {
name string
out *string
}{{"subject", &msg.Subject}, {"plainBody", &msg.TextBody}, {"htmlBody", &msg.HTMLBody}} {
buf := new(bytes.Buffer)
if err := tmpl.ExecuteTemplate(buf, block.name, data); err != nil {
return err
}
*block.out = buf.String()
}
return m.deliver(m.build(recipient, msg))
}

msg := mail.NewMessage()
msg.SetHeader("To", recipient)
// build assembles the email for one recipient.
func (m Mailer) build(recipient string, msg Message) *mail.Message {
out := mail.NewMessage()
out.SetHeader("To", recipient)
if m.senderName != "" {
// smtp_username, address (and SMTP/XOAUTH2 identity) from smtp_sender.
msg.SetAddressHeader("From", m.sender, m.senderName)
out.SetAddressHeader("From", m.sender, m.senderName)
} else {
msg.SetHeader("From", m.sender)
out.SetHeader("From", m.sender)
}
out.SetHeader("Subject", msg.Subject)
switch {
case msg.TextBody != "" && msg.HTMLBody != "":
out.SetBody("text/plain", msg.TextBody)
out.AddAlternative("text/html", msg.HTMLBody)
case msg.HTMLBody != "":
out.SetBody("text/html", msg.HTMLBody)
default:
out.SetBody("text/plain", msg.TextBody)
}
msg.SetHeader("Subject", subject.String())
msg.SetBody("text/plain", plainBody.String())
msg.AddAlternative("text/html", htmlBody.String())
return out
}

// retry sending mail logic
// deliver sends the email, retrying a failed attempt.
func (m Mailer) deliver(msg *mail.Message) error {
const maxRetries = 3
const retrySleep = 500 * time.Millisecond

var err error
for i := range maxRetries {
err = m.dialer.DialAndSend(msg)
if err == nil {
Expand Down
61 changes: 61 additions & 0 deletions api-server/internal/emailer/emailer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package emailer

import (
"bytes"
"strings"
"testing"
)

func render(t *testing.T, msg Message) string {
t.Helper()
var buf bytes.Buffer
if _, err := NewMailer("smtp.example.com", 587, "", "no-reply@example.com", "token").build("to@example.com", msg).WriteTo(&buf); err != nil {
t.Fatal(err)
}
return buf.String()
}

// A message is sent as written: nothing in it is escaped or run as a template.
func TestBuild_SendsTheContentAsWritten(t *testing.T) {
out := render(t, Message{
Subject: "Tom & Jerry's {{.Order}}",
TextBody: "Dear <Name>, a & b",
HTMLBody: "<p>Dear <b>Tom</b> &amp; {{.Order}}</p>",
})

for _, want := range []string{
"Subject: Tom & Jerry's {{.Order}}",
"Content-Type: multipart/alternative",
"Dear <Name>, a & b",
"<p>Dear <b>Tom</b> &amp; {{.Order}}</p>",
} {
if !strings.Contains(out, want) {
t.Errorf("message lacks %q:\n%s", want, out)
}
}
}

// A message with one body is sent with that body alone.
func TestBuild_OneBody(t *testing.T) {
for name, tc := range map[string]struct {
msg Message
wantType string
}{
"text only": {Message{Subject: "s", TextBody: "hello"}, "Content-Type: text/plain"},
"html only": {Message{Subject: "s", HTMLBody: "<p>hello</p>"}, "Content-Type: text/html"},
} {
t.Run(name, func(t *testing.T) {
out := render(t, tc.msg)
if !strings.Contains(out, tc.wantType) || strings.Contains(out, "multipart/alternative") {
t.Errorf("want a single %q part:\n%s", tc.wantType, out)
}
})
}
}

func TestSendMessage_RequiresABody(t *testing.T) {
err := NewMailer("smtp.example.com", 587, "", "no-reply@example.com", "token").SendMessage("to@example.com", Message{Subject: "s"})
if err == nil {
t.Fatal("want an error for a message without a body")
}
}
Loading