goext/googleapi/sendMail.go

70 lines
2.0 KiB
Go
Raw Permalink Normal View History

2023-12-01 18:33:04 +01:00
package googleapi
import (
2023-12-04 13:48:11 +01:00
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"gogs.mikescher.com/BlackForestBytes/goext"
"gogs.mikescher.com/BlackForestBytes/goext/exerr"
2023-12-01 18:33:04 +01:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
2023-12-04 13:48:11 +01:00
"io"
"net/http"
2023-12-01 18:33:04 +01:00
)
2023-12-04 13:48:11 +01:00
type MailRef struct {
ID string `json:"id"`
ThreadID string `json:"threadId"`
LabelIDs []string `json:"labelIds"`
}
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
func (c *client) SendMail(ctx context.Context, from string, recipients []string, cc []string, bcc []string, subject string, body MailBody, attachments []MailAttachment) (MailRef, error) {
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
mm := encodeMimeMail(from, recipients, cc, bcc, subject, body, attachments)
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
tok, err := c.oauth.AccessToken()
if err != nil {
return MailRef{}, exerr.Wrap(err, "").Build()
}
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
url := fmt.Sprintf("https://gmail.googleapis.com/gmail/v1/users/%s/messages/send?alt=json&prettyPrint=false", "me")
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
msgbody, err := json.Marshal(langext.H{"raw": base64.URLEncoding.EncodeToString([]byte(mm))})
if err != nil {
return MailRef{}, exerr.Wrap(err, "").Build()
}
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(msgbody))
if err != nil {
return MailRef{}, exerr.Wrap(err, "").Build()
}
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
req.Header.Add("Authorization", "Bearer "+tok)
req.Header.Add("X-Goog-Api-Client", "blackforestbytes-goext/"+goext.GoextVersion)
req.Header.Add("User-Agent", "blackforestbytes-goext/"+goext.GoextVersion)
req.Header.Add("Content-Type", "application/json")
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
resp, err := c.http.Do(req)
if err != nil {
return MailRef{}, exerr.Wrap(err, "").Build()
2023-12-01 18:33:04 +01:00
}
2023-12-04 13:48:11 +01:00
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return MailRef{}, exerr.Wrap(err, "").Build()
}
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
if resp.StatusCode != 200 {
return MailRef{}, exerr.New(exerr.TypeGoogleStatuscode, "gmail returned non-200 statuscode").Int("sc", resp.StatusCode).Str("body", string(respBody)).Build()
}
2023-12-01 18:33:04 +01:00
2023-12-04 13:48:11 +01:00
var respObj MailRef
err = json.Unmarshal(respBody, &respObj)
if err != nil {
return MailRef{}, exerr.Wrap(err, "").Str("body", string(respBody)).Build()
2023-12-01 18:33:04 +01:00
}
2023-12-04 13:48:11 +01:00
return respObj, nil
2023-12-01 18:33:04 +01:00
}