I'm trying to save an email attachment automatically to map with qmail and reformime. I use the following script:
#!/usr/bin/env bash
# This script process mail message attachments from stdin MIME message
# Extract all PDF files attachments
# and return the MIME message to stdout for further processing
# Ensure all locale settings are set to C, to prevent
# reformime from failing MIME headers decode with
# [unknown character set: ANSI_X3.4-1968]
# See: https://bugs.gentoo.org/304093
export LC_ALL=C LANG=C LANGUAGE=C
# Setting the destination path for saved attachments
attachements='/home/e-smith/files/users/user/attachements/'
trap 'rm -f -- "$mailmessage"' EXIT # Purge temporary mail message
# Create a temporary message file
mailmessage="$(mktemp)"
# Save stdin message to tempfile
cat > "$mailmessage"
# Iterate all MIME sections from the message
while read -r mime_section; do
# Get all section info headers
section_info="$(reformime -s "$mime_section" -i <"$mailmessage")"
# Parse the Content-Type header
content_type="$(grep 'content-type' <<<"$section_info" | cut -d ' ' -f 2-)"
# Parse the Content-Name header (if available)
content_name="$(grep 'content-name' <<<"$section_info" | cut -d ' ' -f 2-)"
# Decode the value of the Content-Name header
content_name="$(reformime -h "$content_name")"
if [[ $content_type = "application/pdf" || $content_name =~ .*\.[pP][dD][fF] ]]; then
# Attachment is a PDF
if [ -z "$content_name" ]; then
# The attachment has no name, so create a random name
content_name="$(mktemp --dry-run unnamed_XXXXXXXX.pdf)"
fi
# Prepend the date to the attachment filename
filename="$(date +%Y%m%d)_$content_name"
# Save the attachment to a file
reformime -s "$mime_section" -e <"$mailmessage" >"$attachements/$filename"
fi
done < <(reformime < "$mailmessage") # reformime list all mime sections
cat <"$mailmessage" # Re-inject the message to stdout for further processing
Problem: the script saves my file name.pdf to "attachements/20191025_[unknown character set: ANSI_X3.4-1968].pdf". So some how reformime does not recognizes the Content-Name: header content. Can this be due to a bad maildrop version? How can I solve this problem?