I am trying to send an email with a CSV attachment, however it is not possible to locally create the file.

Is there any way to pipe the content (I have the content in a variable in memory), to sendmail/mail in a way the data would appear as an attachment?

  • It is possible, of course. If you are willing and able to build the complete MIME mail by hand, you can pipe it to sendmail. IIRC, mail will mangle the result. It mighty be easier to use mutt or mailx. Jun 13 '16 at 6:02
  • Update: both mailx and mutt are unable or unwilling to read an attachment from a fifo, so process substitution doesn't work. Jun 13 '16 at 6:13
  • Hmm, sounds like sendmail or telnet might be my friend here. Jun 13 '16 at 6:21

You can use mailx (example taken from https://access.redhat.com/solutions/104833) and bash <() syntax:

echo "MESSAGE BODY" | mailx -s "SUBJECT" -a <(echo something | sed 's/thing/thong/g') USER@DOM.TLD

Same example with mutt:

echo "MESSAGE BODY" | mutt -s "SUBJECT" -a <(echo something | sed 's/thing/thong/g') -- USER@DOM.TLD

everything in <() will be executed by bash, it will create a temporary file for it and provide it as a parameter for the command.

  • Thanks ! What I was looking for was the <(). Working perfectly. Jun 13 '16 at 7:38
  • 1
    When I try this, I get an empty attachment, like mailx is double touching the file and the second time it does, the file is empty because it was consumed the first time. Using mailx 12.5.
    – CSTobey
    Aug 30 '17 at 15:30

The question doesn't state the reason for not creating a file. Depending on that reason, you might have alternate solutions that allow you to solve the underlying problem in a different way if the approach you asked about doesn't pan out:

  • If the concern is that the file contains sensitive data that you don't want to leave on persistent storage, you can write the file to a ramdisk. Be careful that your mail program doesn't copy the file over to a tmp directory or draft folder.

  • If your concern is that the file is too large to fit into your persistent storage, then you might want to consider that the receiver probably will also have difficulty opening the file and any intermediary MTA. You might want to consider a different protocol instead of the mail protocols.

  • 2
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
    – DavidPostill
    Jun 13 '16 at 16:13
  • @DavidPostill: I disagree with your suggestion. My answer offered an alternative of using ramdisk, which works in most regular email clients, that only accepts real files instead of pipes.
    – Lie Ryan
    Jun 13 '16 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.