概要

Azure Functions から SendGrid を使用してメール送信するサンプルを記載する。
尚、関数アプリは Azure Functions を Go で書く で作成したものをベースとする為、当記事の実装は Go となる。

目次

SendGird アカウントの登録

登録方法による FREEプランの利用枠の違い

Azure Marketplace からと 日本公式サイトから登録できるが、登録方法によってFREEプランの利用枠が異なる。

登録先FEEプランの利用枠
Marketplace25,000通/月
日本公式サイト400通/日

https://sendgrid.kke.co.jp/blog/?p=2621

日単位と月単位で紛らわしいが、Marketplace から登録する方が2倍近くの量を送信できる。

Marketplace から SendGird アカウント登録

TODO:

利用準備

SendGrid API キーの作成/確認

go get

go get github.com/sendgrid/sendgrid-go
go get github.com/joho/godotenv

実装

package main

import (
    "fmt"
    "log"
    "os"
    "strings"

    "github.com/sendgrid/sendgrid-go"
    "github.com/sendgrid/sendgrid-go/helpers/mail"
    "github.com/joho/godotenv"
    "github.com/comail/colog"
)

func loadEnv() {
    if os.Getenv("GO_ENV") == "" {
        os.Setenv("GO_ENV", "dev")
    }

    err_read := godotenv.Load(fmt.Sprintf(".env.%s", os.Getenv("GO_ENV")))
    if err_read != nil {
        log.Printf("info: %v", err_read)
    }
}

func setupLogger() {
   colog.SetDefaultLevel(colog.LInfo)
   colog.SetMinLevel(colog.LTrace)
   colog.SetFormatter(&colog.StdFormatter{
      Colors: true,
      Flag:   log.Ldate | log.Ltime | log.Lshortfile,
   })
   colog.Register()
}

func init(){
    setupLogger()
    loadEnv()
}

func sendmail(subject string, message string){

    API_KEY    := os.Getenv("SENDGRID_API_KEY")
    senderName := os.Getenv("MAIL_FROM_NAME")
    senderMail := os.Getenv("MAIL_FROM_ADDRESS")
    recipients := strings.Split(os.Getenv("MAIL_TO_ADDRESSES"), ",")

    messageText := message
    messageHtml := fmt.Sprintf("<strong style='color: #f00'>%s</strong>", message)

    from := mail.NewEmail(senderName, senderMail)

    email := mail.NewV3Mail()
    email.SetFrom(from)
    email.Subject = subject
    p := mail.NewPersonalization()

    for _, s := range recipients {
        //log.Printf("recipient : %s\n", s)
        to := mail.NewEmail(s, s)
        p.AddTos(to)
    }

    email.AddPersonalizations(p)

    textContent := mail.NewContent("text/plain", messageText)
    htmlContent := mail.NewContent("text/html", messageHtml)
    email.AddContent(textContent, htmlContent)

    client :=  sendgrid.NewSendClient(API_KEY)
    response, err := client.Send(email)
    if err != nil {
        log.Println(err)
    } else if response.StatusCode == 202 {
        log.Printf("info: Mail sended. Status=%d", response.StatusCode)
    } else {
        log.Printf("error: status %d", response.StatusCode)
        log.Printf("error: header %v", response.Headers)
        log.Printf("error: body %s", response.Body)
    }
}

func main() {
    sendmail("メール送信テスト", "メールの本文です")
}

トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS