65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package smtp2shoutrrr
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"log/slog"
|
|
"mime"
|
|
"mime/multipart"
|
|
"net/mail"
|
|
"strings"
|
|
)
|
|
|
|
type ReceivedEmail struct {
|
|
Recipients []string
|
|
Msg *mail.Message
|
|
body string
|
|
}
|
|
|
|
func (re *ReceivedEmail) Body() (string, error) {
|
|
if re.body == "" {
|
|
contentType := re.Msg.Header.Get("Content-Type")
|
|
|
|
if contentType == "" {
|
|
body, err := io.ReadAll(re.Msg.Body)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to read email body: %w", err)
|
|
}
|
|
re.body = string(body)
|
|
} else {
|
|
mediaType, params, err := mime.ParseMediaType(contentType)
|
|
if err != nil {
|
|
log.Fatalf("Failed to parse Content-Type: %v", err)
|
|
}
|
|
|
|
if strings.HasPrefix(mediaType, "multipart/alternative") {
|
|
mr := multipart.NewReader(re.Msg.Body, params["boundary"])
|
|
for {
|
|
part, err := mr.NextPart()
|
|
if err != nil {
|
|
break
|
|
}
|
|
defer part.Close()
|
|
|
|
fmt.Printf("Part Content-Type: %s\n", part.Header.Get("Content-Type"))
|
|
|
|
if strings.HasPrefix(part.Header.Get("Content-Type"), "text/plain") {
|
|
body := new(bytes.Buffer)
|
|
_, err = body.ReadFrom(part)
|
|
if err != nil {
|
|
slog.Error("Failed to read part body", slog.String("err", err.Error()))
|
|
return "", fmt.Errorf("failed to read part body: %w", err)
|
|
}
|
|
|
|
re.body = body.String()
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return re.body, nil
|
|
}
|