From af0a2b9a46e5d7f015682ebc1522bd421d7fe3dd Mon Sep 17 00:00:00 2001 From: Reto Brunner Date: Tue, 15 Dec 2020 21:48:25 +0100 Subject: Use extensions for querying the mime type of attachments This gets rid of the issue that lots of things are detected as zip files, even though they are a more specialized format (say office files) --- widgets/compose.go | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/widgets/compose.go b/widgets/compose.go index 73ebcb3e..e139f9ac 100644 --- a/widgets/compose.go +++ b/widgets/compose.go @@ -460,8 +460,6 @@ func writeMultipartBody(body io.Reader, w *mail.Writer) error { // write the attachment specified by path to the message func writeAttachment(path string, writer *mail.Writer) error { - filename := filepath.Base(path) - f, err := os.Open(path) if err != nil { return errors.Wrap(err, "os.Open") @@ -470,20 +468,30 @@ func writeAttachment(path string, writer *mail.Writer) error { reader := bufio.NewReader(f) - // determine the MIME type - // http.DetectContentType only cares about the first 512 bytes - head, err := reader.Peek(512) - if err != nil && err != io.EOF { - return errors.Wrap(err, "Peek") + // if we have an extension, prefer that instead of trying to sniff the header. + // That's generally more accurate than sniffing as lots of things are zip files + // under the hood, e.g. most office file types + ext := filepath.Ext(path) + var mimeString string + if mimeString = mime.TypeByExtension(ext); mimeString != "" { + // found it in the DB + } else { + // Sniff the mime type instead + // http.DetectContentType only cares about the first 512 bytes + head, err := reader.Peek(512) + if err != nil && err != io.EOF { + return errors.Wrap(err, "Peek") + } + mimeString = http.DetectContentType(head) } - mimeString := http.DetectContentType(head) // mimeString can contain type and params (like text encoding), // so we need to break them apart before passing them to the headers mimeType, params, err := mime.ParseMediaType(mimeString) if err != nil { return errors.Wrap(err, "ParseMediaType") } + filename := filepath.Base(path) params["name"] = filename // set header fields -- cgit