0

Here is my scenario. I have a txt file. emailADD.txt. it contains email ids every line

[email protected]
[email protected]
[email protected]

And i have files in a folder

abc.pdf
def.pdf
hij.pdf

and so on

i want a script to send email to the first id with the first attachment. then another email to second id with the second attachment and so on.

both email ids and the attachments will be stored in alphabetical order. the number of email ids and attachments stored will be equal.

Please suggest.

I have this idea from jesse_b but it doesn't involve different attachments to each email id.

#!/bin/bash
file=/location/of/emailAdd.txt

while 
    read -r email; 
    do
      #printf '%s\n' 'Hello, world!' | sudo mail -s 'This is the email subject' "$email"
    done < "$file"

2 Answers 2

1

I think it would be easier to start from looping through attachments and extract recipient along the way since shell will expand glob in an alphabetical order. Your script could look like this:

#!/usr/bin/env sh

line=1

for i in *.pdf
do
    echo "$i"
    recipient="$(awk -v line="$line" 'NR==line' emailADD.txt)"
    if [ -n "$recipient" ]
    then
        printf "recipient: %s\n" "$recipient"
        line=$((line+1))
        printf '%s\n' 'Hello, world!' | echo mail -s 'This is the email subject' -a "$i" "$recipient"
    fi
done

Remove echo to actually run mail command but run it first with it to make sure that it will do what you need.

1

If you're going to be sending a boatload of emails, you might get better performance by avoiding the opening of emailADD.txt once per attachment. If you're using bash you can use <() to process the attachments without storing their names in a file:

$ paste emailADD.txt <(ls folder/) | while read -r email pdf; do printf '%s\n' 'Hello, world!' | echo mail -s 'This is the email subject' -a "$pdf" "$email"; done

You can remove the echo once it seems like it will do what you want.

However, if you won't be running this in an automatic/regular fashion, consider generating the text of the full commands (including the printf), redirecting the output to a file, and then execute the commands in that file. That allows inspection of the commands, avoids surprises if emailADD.txt or the attachment list changes mid-run, and gives you a record of what was done (which can be saved or discarded). Like this:

$ paste emailADD.txt <(ls folder/) | while read -r email pdf; do echo "printf '%s\n' 'Hello, world' | mail -s 'This is the email subject' -a '$pdf' '$email' " ; done >| cmds

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.