How to send email with attachment by postfix from command-line?

Solution 1:

Why does it have to be postfix directly? mailx -a, mutt, or mutt -a will also use the sendmail interface -- unless you configure them for SMTP.

echo "This is a test message" | mutt -s Test -a foo.zip -- $USER
echo "This is a test message" | mail -s Test -a foo.zip $USER

(Note, in bsd-mailx the option is -A instead.)


Anyway, here's a "postfix" example.

Replace $USER, content type and filename to match your environment. Example assumes you are sending the message to yourself and have a ZIP file foo.zip in the current directory.

(printf "%s\n" \
    "Subject: test" \
    "To: $USER" \
    "Content-Type: application/zip" \
    "Content-Disposition: attachment; filename=foo.zip" \
    "Content-Transfer-Encoding: base64" \
    "";
 base64 foo.zip) | sendmail "$USER"

(Creation of MIME multipart messages left as an exercise to the reader.)

Solution 2:

Postfix is a mail transfer agent (MTA). Its job is to handle the delivery of the mail: pick it up and send it to the next point on its route. Postfix is a postal worker, whose job is to take an envelope and (with help from its colleagues) carry it to the recipient.

What you're asking for here is secretarial work: assembling documents to put them in the envelope. That's not Postfix's job: it's a job for a mail user agent (MUA). You can write a crude MUA that just assembles pieces to make a mail in a few lines of shell, as grawity did, but Mutt is really a good tool for this task.

Solution 3:

From the command line, I like to use "sendemail", which on ubuntu / debian can be installed from the command line like so:

apt-get install sendemail

Then you can simply tell it to use localhost (Postfix) as the MTA.

Actually I just noticed that localhost:25 is the default:

-s SERVER[:PORT]          smtp mail relay, default is localhost:25

You then add attachments using the -a flag:

sendemail -f [email protected] -t [email protected] -m "This is the message" -u "This is the subject" -a file1.zip file2.zip