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)
This commit is contained in:
Reto Brunner 2020-12-15 21:48:25 +01:00
parent 83202dcb2e
commit af0a2b9a46
1 changed files with 16 additions and 8 deletions

View File

@ -460,8 +460,6 @@ func writeMultipartBody(body io.Reader, w *mail.Writer) error {
// write the attachment specified by path to the message // write the attachment specified by path to the message
func writeAttachment(path string, writer *mail.Writer) error { func writeAttachment(path string, writer *mail.Writer) error {
filename := filepath.Base(path)
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
return errors.Wrap(err, "os.Open") return errors.Wrap(err, "os.Open")
@ -470,20 +468,30 @@ func writeAttachment(path string, writer *mail.Writer) error {
reader := bufio.NewReader(f) reader := bufio.NewReader(f)
// determine the MIME type // 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 // http.DetectContentType only cares about the first 512 bytes
head, err := reader.Peek(512) head, err := reader.Peek(512)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
return errors.Wrap(err, "Peek") return errors.Wrap(err, "Peek")
} }
mimeString = http.DetectContentType(head)
}
mimeString := http.DetectContentType(head)
// mimeString can contain type and params (like text encoding), // mimeString can contain type and params (like text encoding),
// so we need to break them apart before passing them to the headers // so we need to break them apart before passing them to the headers
mimeType, params, err := mime.ParseMediaType(mimeString) mimeType, params, err := mime.ParseMediaType(mimeString)
if err != nil { if err != nil {
return errors.Wrap(err, "ParseMediaType") return errors.Wrap(err, "ParseMediaType")
} }
filename := filepath.Base(path)
params["name"] = filename params["name"] = filename
// set header fields // set header fields