Skip to content

Commit e3f7298

Browse files
author
isch
committed
Added parsing attachments in non-multipart emails
1 parent d916cfb commit e3f7298

1 file changed

Lines changed: 28 additions & 2 deletions

File tree

parsemail.go

Lines changed: 28 additions & 2 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,29 @@ 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+
attachmentData, err := decodeContent(body, header.Get("Content-Transfer-Encoding"))
111+
contentDisposition := header.Get("Content-Disposition")
112+
113+
if err != nil {
114+
return attachments, err
115+
}
116+
117+
if len(contentDisposition) > 0 && strings.Contains(contentDisposition, "attachment;") {
118+
fileName := strings.Replace(contentDisposition, "attachment; filename=\"", "", -1)
119+
fileName = strings.TrimRight(fileName, "\"")
120+
121+
at := Attachment{
122+
Filename: fileName,
123+
ContentType: "application/octet-stream",
124+
Data: attachmentData,
125+
}
126+
attachments = append(attachments, at)
127+
}
128+
129+
return attachments, nil
130+
}
131+
106132
func parseMultipartRelated(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
107133
pmr := multipart.NewReader(msg, boundary)
108134
for {
@@ -483,11 +509,11 @@ type Email struct {
483509
ResentMessageID string
484510

485511
ContentType string
486-
Content io.Reader
512+
Content io.Reader
487513

488514
HTMLBody string
489515
TextBody string
490516

491517
Attachments []Attachment
492518
EmbeddedFiles []EmbeddedFile
493-
}
519+
}

0 commit comments

Comments
 (0)