方法1:net/smtp
Goの標準ライブラリに必要なものはすべて揃っています。HTMLメールには、メッセージ本文にMIMEのcontent-typeヘッダーを手動で書き込む必要があります:
package main
import (
"net/smtp"
"os"
)
func main() {
apiKey := os.Getenv("SENDCOREX_API_KEY")
auth := smtp.PlainAuth("", apiKey, apiKey, "smtp.sendcorex.com")
to := []string{"customer@example.com"}
msg := []byte("To: customer@example.com\r\n" +
"From: Your App <hello@yourdomain.com>\r\n" +
"Subject: Welcome!\r\n" +
"Content-Type: text/html; charset=UTF-8\r\n\r\n" +
"<h1>You are in.</h1>")
err := smtp.SendMail("smtp.sendcorex.com:587", auth, "hello@yourdomain.com", to, msg)
if err != nil {
panic(err)
}
}
方法2:net/httpでREST API
body := []byte(`{"to":"customer@example.com","from":"hello@yourdomain.com","subject":"Welcome!","html":"<h1>You are in.</h1>"}`)
req, _ := http.NewRequest("POST", "https://graph.sendcorex.com/v3.0/emails", bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
よくあるエラー
| 症状 | 対処 |
|---|---|
535 Authentication failed | APIキーが正しく、PlainAuthの両方のフィールドに使われているか確認してください。 |
| メッセージがプレーンテキストで表示される | Content-Type: text/htmlヘッダーは、空行より前の生のメッセージに含める必要があります。 |