refactor: Reorganize SMTP2Shoutrrr code into separate files
This commit is contained in:
parent
9625807106
commit
31f2102031
4 changed files with 232 additions and 222 deletions
65
email.go
Normal file
65
email.go
Normal file
|
@ -0,0 +1,65 @@
|
|||
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
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue