Skip to content

Commit

Permalink
feat: initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
darylhjd committed Feb 9, 2024
0 parents commit a685f74
Show file tree
Hide file tree
Showing 9 changed files with 314 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Enforce LF line endings regardless of OS or git configurations.
* text=auto eol=lf
21 changes: 21 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
vendor/

# Go workspace file
go.work
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Har Jing Daryl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# azmail

[![Go Reference](https://pkg.go.dev/badge/github.com/darylhjd/azmail.svg)](https://pkg.go.dev/github.com/darylhjd/azmail)
[![Go Report](https://goreportcard.com/badge/github.com/darylhjd/azmail?style=flat-square)](https://goreportcard.com/report/github.com/darylhjd/azmail)

Go API for sending emails through Microsoft Azure's Email Communication Service.

## Installation

```cmd
$ go get -u github.com/darylhjd/azmail
```

## Example Usage

```go
package main

import (
"log"

"github.com/darylhjd/azmail"
)

func main() {
client, _ := azmail.NewClient("ENDPOINT", "ACCESS_KEY", "SENDER_ADDRESS")

// Create mails that you want to send.
mail1 := azmail.NewMail()
mail1.Recipients = ...
mail1.Content = ...
mail1.Attachments = ...
mail2 := azmail.NewMail()
...

// Send your mails.
errs := client.SendMails(mail1, mail2)
log.Println(errs)
}
```

## Current Version and Documentation

This wrapper implements version `2023-03-31` of the Email API.

More information on the API can be
found [here](https://learn.microsoft.com/en-us/rest/api/communication/dataplane/email/send?view=rest-communication-dataplane-2023-03-31&viewFallbackFrom=rest-communication-dataplane-2023-10-01&tabs=HTTP).
44 changes: 44 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package azmail

import (
"encoding/base64"
"net/url"
)

const (
apiPath = "/emails:send"
apiVersion = "2023-03-31"
)

// Client for the Azure Email Communication Service.
type Client struct {
u *url.URL
accessKey []byte

senderAddr string
}

// NewClient creates a new client for Azure Email Communication Service.
// Use the provided endpoint, access key, and email address from your communication service.
func NewClient(endpoint, accessKey, senderAddr string) (*Client, error) {
rawKey, err := base64.StdEncoding.DecodeString(accessKey)
if err != nil {
return nil, err
}

u, err := url.Parse(endpoint)
if err != nil {
return nil, err
}

v := url.Values{}
v.Set("api-version", apiVersion)
u.RawQuery = v.Encode()
u.Path = apiPath

return &Client{
u: u,
accessKey: rawKey,
senderAddr: senderAddr,
}, nil
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/darylhjd/azmail

go 1.21.5
35 changes: 35 additions & 0 deletions mail.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package azmail

type Mail struct {
Recipients MailRecipients `json:"recipients"`
Content MailContent `json:"content"`
Attachments []MailAttachment `json:"attachments"`
}

type MailRecipients struct {
To []MailAddress `json:"to"`
Cc []MailAddress `json:"cc"`
Bcc []MailAddress `json:"bcc"`
}

type MailAddress struct {
Address string `json:"address"`
DisplayName string `json:"displayName"`
}

type MailContent struct {
Subject string `json:"subject"`
PlainText string `json:"plainText"`
Html string `json:"html"`
}

type MailAttachment struct {
Name string `json:"name"`
Base64Content string `json:"contentInBase64"`
ContentType string `json:"contentType"`
}

// NewMail is a convenience function for creating a new Mail and returning the pointer to it.
func NewMail() *Mail {
return &Mail{}
}
86 changes: 86 additions & 0 deletions send.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package azmail

import (
"bytes"
"encoding/json"
"errors"
"net/http"
)

type mailMessage struct {
Attachments []MailAttachment `json:"attachments"`
Content MailContent `json:"content"`
Recipients MailRecipients `json:"recipients"`
ReplyTo []MailAddress `json:"replyTo"`
SenderAddr string `json:"senderAddress"`
UserEngagementTrackingDisabled bool `json:"userEngagementTrackingDisabled"`
}

func (c *Client) newMailMessage(mail Mail) mailMessage {
return mailMessage{
nil,
mail.Content,
mail.Recipients,
nil,
c.senderAddr,
true,
}
}

// SendMails sends multiple mails. If any errors are encountered, the error is saved and later returned.
// Encountering errors does not stop later emails from being sent.
func (c *Client) SendMails(mails ...*Mail) error {
var errs []error

for _, mail := range mails {
msg := c.newMailMessage(*mail)
if err := c.sendMessage(msg); err != nil {
errs = append(errs, err)
}
}

return errors.Join(errs...)
}

type errorResponse struct {
Error struct {
AdditionalInfo []struct {
Info any `json:"info"`
Type string `json:"type"`
} `json:"additionalInfo"`
Code string `json:"code"`
Details []errorResponse `json:"details"`
Message string `json:"message"`
Target string `json:"target"`
} `json:"error"`
}

func (c *Client) sendMessage(msg mailMessage) error {
req, err := c.generateSignedMessageRequest(msg)
if err != nil {
return err
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}

if resp.StatusCode == http.StatusAccepted {
return nil
}

var (
b bytes.Buffer
errResp errorResponse
)
if _, err = b.ReadFrom(resp.Body); err != nil {
return err
}

if err = json.Unmarshal(b.Bytes(), &errResp); err != nil {
return err
}

return errors.New(errResp.Error.Message)
}
55 changes: 55 additions & 0 deletions sign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package azmail

import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)

func (c *Client) generateSignedMessageRequest(msg mailMessage) (*http.Request, error) {
// https://learn.microsoft.com/en-us/rest/api/communication/dataplane/email/send?view=rest-communication-dataplane-2023-03-31&viewFallbackFrom=rest-communication-dataplane-2023-04-01-preview&tabs=HTTP
body, err := json.Marshal(msg)
if err != nil {
return nil, err
}

req, err := http.NewRequest(http.MethodPost, c.u.String(), bytes.NewReader(body))
if err != nil {
return nil, err
}

// https://learn.microsoft.com/en-us/rest/api/communication/authentication
pathAndQuery := fmt.Sprintf("%s?%s", c.u.Path, c.u.Query().Encode())

timestamp := strings.ReplaceAll(time.Now().UTC().Format(time.RFC1123), "UTC", "GMT")

hash := sha256.Sum256(body)
hashB64 := base64.StdEncoding.EncodeToString(hash[:])

stringToSign := fmt.Sprintf(
"%s\n%s\n%s;%s;%s",
http.MethodPost, pathAndQuery, timestamp, c.u.Host, hashB64,
)

hm := hmac.New(sha256.New, c.accessKey)
if _, err = hm.Write([]byte(stringToSign)); err != nil {
return nil, err
}

signature := base64.StdEncoding.EncodeToString(hm.Sum(nil))
authorization := fmt.Sprintf("HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256&Signature=%s", signature)

req.Header.Set("Content-Type", "application/json")
req.Header["x-ms-date"] = []string{timestamp}
req.Header["x-ms-content-sha256"] = []string{hashB64}
req.Header["host"] = []string{pathAndQuery}
req.Header.Set("Authorization", authorization)

return req, nil
}

0 comments on commit a685f74

Please sign in to comment.