Skip to content

Commit

Permalink
refactor: encapsulate lib functions further
Browse files Browse the repository at this point in the history
  • Loading branch information
windvalley committed Jul 2, 2023
1 parent f0386a1 commit f338a2d
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 15 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## v0.2.1

### Changed

- 优化`Parse``ParseHeader``ParseBody`函数的传参, 进一步封装, 使更易用

## v0.2.0

### Added
Expand Down
10 changes: 2 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package main
import (
"fmt"
"log"
"net/mail"

"github.com/knadh/go-pop3"

Expand Down Expand Up @@ -58,13 +57,8 @@ func main() {
continue
}

m, err := mail.ReadMessage(b)
if err != nil {
fmt.Println(err)
continue
}

res, err := mailparser.Parse(m)
// parse email
res, err := mailparser.Parse(b)
if err != nil {
fmt.Println(err)
continue
Expand Down
24 changes: 17 additions & 7 deletions mailparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import (
)

const (
// multipart/alternative, multipart/mixed, multipart/related
// multipart/alternative, multipart/mixed, multipart/related...
multipartPrefix = "multipart/"
// text/html, text/plain
// text/html, text/plain, text/markdown...
textPrefix = "text/"
)

Expand Down Expand Up @@ -52,13 +52,13 @@ type MailMessage struct {
}

// Parse mail message.
func Parse(m *mail.Message) (*MailMessage, error) {
header, err := ParseHeader(m)
func Parse(r io.Reader) (*MailMessage, error) {
header, err := ParseHeader(r)
if err != nil {
return nil, err
}

body, attachments, err := ParseBody(m)
body, attachments, err := ParseBody(r)
if err != nil {
return nil, err
}
Expand All @@ -71,7 +71,12 @@ func Parse(m *mail.Message) (*MailMessage, error) {
}

// ParseHeader mail message headers.
func ParseHeader(m *mail.Message) (*Header, error) {
func ParseHeader(r io.Reader) (*Header, error) {
m, err := mail.ReadMessage(r)
if err != nil {
return nil, err
}

dec := new(mime.WordDecoder)
dec.CharsetReader = charsetReader

Expand Down Expand Up @@ -130,7 +135,12 @@ func ParseHeader(m *mail.Message) (*Header, error) {
}

// ParseBody mail message body.
func ParseBody(m *mail.Message) (string, []*Attachment, error) {
func ParseBody(r io.Reader) (string, []*Attachment, error) {
m, err := mail.ReadMessage(r)
if err != nil {
return "", nil, err
}

contentType := m.Header.Get("Content-Type")
if contentType == "" {
contentType = "text/plain"
Expand Down

0 comments on commit f338a2d

Please sign in to comment.