66 lines
1.6 KiB
Go
66 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
mailgun "github.com/mailgun/mailgun-go/v3"
|
|
|
|
_ "github.com/joho/godotenv/autoload"
|
|
)
|
|
|
|
func main() {
|
|
/*
|
|
MAILGUN_API_KEY=key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
MAILGUN_DOMAIN=mail.example.com
|
|
MAILER_FROM="Rob the Robot <rob.the.robot@mail.example.com>"
|
|
*/
|
|
|
|
to := flag.String("to", "", "message recipient in the format of 'John Doe <john@example.com>'")
|
|
replyTo := flag.String("reply-to", "", "reply-to in the format of 'John Doe <john@example.com>'")
|
|
subject := flag.String("subject", "Test Subject", "the utf8-encoded subject of the email")
|
|
text := flag.String(
|
|
"text",
|
|
"Testing some Mailgun awesomeness!",
|
|
"the body of the email as utf8-encoded plain-text format",
|
|
)
|
|
flag.Parse()
|
|
|
|
if 0 == len(*to) {
|
|
flag.Usage()
|
|
os.Exit(1)
|
|
}
|
|
|
|
domain := os.Getenv("MAILGUN_DOMAIN")
|
|
apiKey := os.Getenv("MAILGUN_API_KEY")
|
|
from := os.Getenv("MAILER_FROM")
|
|
|
|
if 0 == len(*text) {
|
|
*text = "Testing some Mailgun awesomeness!"
|
|
}
|
|
|
|
msgId, err := SendSimpleMessage(domain, apiKey, *to, from, *subject, *text, *replyTo)
|
|
if nil != err {
|
|
panic(err)
|
|
}
|
|
fmt.Printf("Queued with Message ID %q\n", msgId)
|
|
}
|
|
|
|
func SendSimpleMessage(domain, apiKey, to, from, subject, text, replyTo string) (string, error) {
|
|
mg := mailgun.NewMailgun(domain, apiKey)
|
|
m := mg.NewMessage(from, subject, text, to)
|
|
if 0 != len(replyTo) {
|
|
// mailgun's required "h:" prefix is added by the library
|
|
m.AddHeader("Reply-To", replyTo)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
|
|
defer cancel()
|
|
|
|
_, id, err := mg.Send(ctx, m)
|
|
return id, err
|
|
}
|