Skip to content

Commit daeeb1b

Browse files
authored
Merge pull request #4 from get-net/fns_attachments_fix
Parse email with just a binary attachment and no text
2 parents 1b45663 + e9e98d0 commit daeeb1b

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
module github.com/DusanKasan/parsemail
1+
module github.com/get-net/parsemail
22

33
go 1.12

parsemail.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ const contentTypeMultipartAlternative = "multipart/alternative"
1818
const contentTypeMultipartRelated = "multipart/related"
1919
const contentTypeTextHtml = "text/html"
2020
const contentTypeTextPlain = "text/plain"
21+
const contentTypeOctetStream = "application/octet-stream"
2122

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

109+
func parseAttachmentOnlyEmail(body io.Reader, header mail.Header) (attachments []Attachment, err error) {
110+
contentDisposition := header.Get("Content-Disposition")
111+
112+
if len(contentDisposition) > 0 && strings.Contains(contentDisposition, "attachment;") {
113+
114+
attachmentData, err := decodeContent(body, header.Get("Content-Transfer-Encoding"))
115+
if err != nil {
116+
return attachments, err
117+
}
118+
119+
fileName := strings.Replace(contentDisposition, "attachment; filename=\"", "", -1)
120+
fileName = strings.TrimRight(fileName, "\"")
121+
122+
at := Attachment{
123+
Filename: fileName,
124+
ContentType: "application/octet-stream",
125+
Data: attachmentData,
126+
}
127+
128+
attachments = append(attachments, at)
129+
}
130+
131+
return attachments, nil
132+
}
133+
106134
func parseMultipartRelated(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
107135
pmr := multipart.NewReader(msg, boundary)
108136
for {

0 commit comments

Comments
 (0)