Sunday, October 23, 2005

Sending mail from the command line with Mutt

During the migration to Blogger, I used the post-by-mail service to ease the move of all posts. I downloaded all the old ones into my computer and then automatically sent a mail for each of them to the appropriate posting address.

However, this was not easy. As all the posts were in HTML format, I needed to tell the mailer to send a multipart message with a text/html part. After many attempts, NetBSD's mail(1) command proved to be insufficient so I had to look for another mailing utility to do the same thing. (Note that I know few things about the mail protocol, so I can be missing something.)

My first thought was that Mutt could help. Indeed, if I composed an empty mail and attached an HTML file, it did what I wanted. The problem came when I had to automate this from a script... The first attempt was something like:

mutt -s "$(cat mail/$f.subject)" -a mail/$f.html address@example.org

Ok, this worked, but having to type [Enter][Enter], then :wq and then y for each message was not automatic. The first thing I solved was the save and edit part from the editor. Instead of using vi(1), I asked Mutt to use touch(1):

EDITOR=touch mutt -s "$(cat mail/$f.subject)" -a mail/$f.html address@example.org

This solved the :wq part but I still had to type [Enter][Enter]y for each post. How to solve it... I searched a bit (I mean, Googleed a bit) and found that giving /dev/null as the standard input to Mutt was enough to silence it. So the command ended being as:

EDITOR=touch mutt -s "$(cat mail/$f.subject)" -a mail/$f.html address@example.org </dev/null

Still, it'd be nice if the standard mail(1) utility was able to send complex messages...

6 comments:

Anonymous said...

Since the 'standard' mailers can't read MIME as MIME, nor deal with HTML, its not that suprising they don't deal with attachments or with HTML content well.

HTML mail is anathema!

George, using MH since 1982...

Anonymous said...

try this:

mutt -s "$(cat mail/$f.subject)" -a mail/$f.html address@example.org < /dev/null

Anonymous said...

Awesome! I have been trying to figure out how to send email from a script for a few days now. Thanks!

Lawrence said...

Soooooo useful!

Anonymous said...

Alternately, I use:
echo "Email body" | mutt -s "Email Title" -a myattachement.txt address@example.org

Anonymous said...

I'm able to send from command line with mutt (and esmtp), but only for any non-root user. With root, I get an error: "StartTLS extension not supported by MTA", but it IS supported, as others users can send mail!! I'm using a gmail account, and have certificates and authentication for that.

The file $HOME/user/.muttrc is identical to /root.muttrc. Any other config file (e.g. /etc/Muttrc.d/* or /etc/esmtprc) doesn't mention anything related to users (root/non-root).

I use Ubuntu Gutsy (7.10), esmtp 0.5.1-4.1 and mutt 1.5.15+20070412.

Thanks for any ideas.

Jose Luis