Skip to content

Commit

Permalink
Merge pull request #4 from get-net/fns_attachments_fix
Browse files Browse the repository at this point in the history
Parse email with just a binary attachment and no text
  • Loading branch information
k3a committed Aug 26, 2023
2 parents 1b45663 + e9e98d0 commit daeeb1b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/DusanKasan/parsemail
module github.com/get-net/parsemail

go 1.12
28 changes: 28 additions & 0 deletions parsemail.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const contentTypeMultipartAlternative = "multipart/alternative"
const contentTypeMultipartRelated = "multipart/related"
const contentTypeTextHtml = "text/html"
const contentTypeTextPlain = "text/plain"
const contentTypeOctetStream = "application/octet-stream"

// Parse an email message read from io.Reader into parsemail.Email struct
func Parse(r io.Reader) (email Email, err error) {
Expand Down Expand Up @@ -50,6 +51,8 @@ func Parse(r io.Reader) (email Email, err error) {
case contentTypeTextHtml:
message, _ := ioutil.ReadAll(msg.Body)
email.HTMLBody = strings.TrimSuffix(string(message[:]), "\n")
case contentTypeOctetStream:
email.Attachments, err = parseAttachmentOnlyEmail(msg.Body, msg.Header)
default:
email.Content, err = decodeContent(msg.Body, msg.Header.Get("Content-Transfer-Encoding"))
}
Expand Down Expand Up @@ -103,6 +106,31 @@ func parseContentType(contentTypeHeader string) (contentType string, params map[
return mime.ParseMediaType(contentTypeHeader)
}

func parseAttachmentOnlyEmail(body io.Reader, header mail.Header) (attachments []Attachment, err error) {
contentDisposition := header.Get("Content-Disposition")

if len(contentDisposition) > 0 && strings.Contains(contentDisposition, "attachment;") {

attachmentData, err := decodeContent(body, header.Get("Content-Transfer-Encoding"))
if err != nil {
return attachments, err
}

fileName := strings.Replace(contentDisposition, "attachment; filename=\"", "", -1)
fileName = strings.TrimRight(fileName, "\"")

at := Attachment{
Filename: fileName,
ContentType: "application/octet-stream",
Data: attachmentData,
}

attachments = append(attachments, at)
}

return attachments, nil
}

func parseMultipartRelated(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
pmr := multipart.NewReader(msg, boundary)
for {
Expand Down

0 comments on commit daeeb1b

Please sign in to comment.