0

I have list of excel files in a directory. I'm trying to email those files as attachment. However, when I open the email, I could see only one file as attachment. The below script is not attaching multiple files as attachment.

ls *.xls;
#echo "Test Email" | mailx -s "Testing File Conv" -a *.xls test@testmail.com

Will the above script work?

Jenifer
  • 387
  • 2
  • 11
  • 1
    I don't use `mailx` but try repeating `-a` for a couple of files, i.e. `mailx -s "Subject" -a file1.xls -a file2.xls ...` and see if it works. – Mark Setchell Nov 07 '22 at 08:01

2 Answers2

3

An array can be built to hold all the attachment options for each file like this:

#!/usr/bin/env bash

# Produces no result if no match for pattern
shopt -s nullglob

# Captures recipients from script arguments
recipients=("$@")

# Populates aray with xls file paths
xls_files=(./*.xls)

# If there are xls files
if [ "${#xls_files[@]}" -gt 0 ]; then

  # Declare an array to store mailx attachment options
  attach_option=()

  # Creates an attachment option for each file to be attached
  for file in "${xls_files[@]}"; do
    attach_option+=(-a "$file")
  done

  # Sends mail with all the attachment options
  mailx -s "Testing File Conv" "${attach_option[@]}" "${recipients[@]}"
fi
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
-1

You have to write a script for this. at first create test.txt.

ls *.xls -1 > test.txt

then run this script :

while read line
do
mailx -s "Subject" -a ${line} -s "files" ${mail_from} << EOM

Hi, Sent files

EOM

done<test.txt
rezshar
  • 570
  • 1
  • 6
  • 20
  • 2
    Using the output of `ls` to parse and using `read` without a `-r` switch, are both bad practices. – Léa Gris Nov 07 '22 at 07:58
  • 2
    You simply want `for line in *.xls`; also [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Nov 07 '22 at 08:40