Skip to content

Instantly share code, notes, and snippets.

@qdm12
Created May 11, 2021 14:39
Show Gist options
  • Save qdm12/2b35e406a86368b7f44a42c459a9958e to your computer and use it in GitHub Desktop.
Save qdm12/2b35e406a86368b7f44a42c459a9958e to your computer and use it in GitHub Desktop.
Fetch API and send email (@clemone210)
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"net/smtp"
"os"
"os/signal"
"time"
)
func main() {
ctx, stop := signal.NotifyContext(
context.Background(), os.Interrupt, os.Kill)
defer stop()
const httpTimeout = 10 * time.Second
client := &http.Client{
Timeout: httpTimeout,
}
const (
restAPI = "https://domain.com/v1"
url = restAPI + "/resource/321312"
)
result, err := getAPIData(ctx, client, url)
if err != nil {
log.Println(err)
return
}
const (
smtpUser = "user"
smtpPassword = "password"
smtpServerHost = "mail.example.com:25"
recipient = "[email protected]"
sender = "[email protected]"
)
err = sendMailWithSMTP(smtpUser, smtpPassword,
smtpServerHost, recipient, sender, result)
if err != nil {
log.Println(err)
return
}
log.Println("Email successfully sent to " + recipient + " with API result " + result)
}
func getAPIData(ctx context.Context, client *http.Client, url string) (
result string, err error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", err
}
response, err := client.Do(request)
if err != nil {
return "", err
}
if response.StatusCode != http.StatusOK {
_ = response.Body.Close()
return "", fmt.Errorf("Bad HTTP status code: " + response.Status)
}
data, err := io.ReadAll(response.Body)
if err != nil {
return "", err
}
if err := response.Body.Close(); err != nil {
return "", err
}
return string(data), nil
}
func sendMailWithSMTP(user, password, serverHost,
recipient, sender, apiResult string) (err error) {
hostname, _, err := net.SplitHostPort(serverHost)
if err != nil {
return err
}
auth := smtp.PlainAuth("", user, password, hostname)
recipients := []string{recipient}
message := []byte("To: " + recipient + "\r\n" +
"Subject: REST API response\r\n" +
"\r\n" +
"Response is:" + apiResult + ".\r\n")
return smtp.SendMail(serverHost, auth, sender, recipients, message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment