Skip to content

Commit

Permalink
Add mailgun handler (WIP)
Browse files Browse the repository at this point in the history
  • Loading branch information
rowanseymour committed Jan 19, 2024
1 parent c8a4f66 commit a31e536
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/courier/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import (
_ "github.com/nyaruka/courier/handlers/line"
_ "github.com/nyaruka/courier/handlers/m3tech"
_ "github.com/nyaruka/courier/handlers/macrokiosk"
_ "github.com/nyaruka/courier/handlers/mailgun"
_ "github.com/nyaruka/courier/handlers/mblox"
_ "github.com/nyaruka/courier/handlers/messagebird"
_ "github.com/nyaruka/courier/handlers/messangi"
Expand Down
79 changes: 79 additions & 0 deletions handlers/mailgun/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package mailgun

import (
"bytes"
"context"
"fmt"
"mime/multipart"
"net/http"

"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
)

const (
configSubject = "subject"
)

var (
defaultAPIURL = "https://api.mailgun.net/v3"
)

func init() {
courier.RegisterHandler(newHandler())
}

type handler struct {
handlers.BaseHandler
}

func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("MLG"), "Mailgun")}
}

func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
s.AddHandlerRoute(h, http.MethodPost, "receive", courier.ChannelLogTypeMsgReceive, h.receive)
return nil
}

func (h *handler) receive(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request, clog *courier.ChannelLog) ([]courier.Event, error) {
// TODO
return nil, nil
}

func (h *handler) Send(ctx context.Context, msg courier.MsgOut, clog *courier.ChannelLog) (courier.StatusUpdate, error) {
domain := msg.Channel().Address()
sendURL := fmt.Sprintf("%s/%s/messages", defaultAPIURL, domain)

sendingKey := msg.Channel().StringConfigForKey(courier.ConfigAuthToken, "")
if sendingKey == "" {
return nil, fmt.Errorf("missing sending key for %s channel", h.ChannelName())
}

subject := msg.Channel().StringConfigForKey(configSubject, "Chat with TextIt")

b := &bytes.Buffer{}
w := multipart.NewWriter(b)
w.WriteField("from", fmt.Sprintf("no-reply@%s", domain))
w.WriteField("to", msg.URN().Path())
w.WriteField("subject", subject)
w.WriteField("text", msg.Text())

// TODO add attachments

w.Close()

req, _ := http.NewRequest("POST", sendURL, b)
req.Header.Set("Content-Type", w.FormDataContentType())
req.SetBasicAuth("api", sendingKey)

status := h.Backend().NewStatusUpdate(msg.Channel(), msg.ID(), courier.MsgStatusWired, clog)

resp, _, err := h.RequestHTTP(req, clog)
if err != nil || resp.StatusCode/100 != 2 {
status.SetStatus(courier.MsgStatusErrored)
}

return status, nil
}

0 comments on commit a31e536

Please sign in to comment.