Bash Script to Send Email Notification Easily
mail command in Bash like this: echo "Message body" | mail -s "Subject" recipient@example.com to send an email notification.Examples
How to Think About It
mail. You provide the message body via standard input and specify the subject and recipient as command options.Algorithm
Code
#!/bin/bash message="Hello, this is a notification from your script." subject="Notification" recipient="user@example.com" echo "$message" | mail -s "$subject" "$recipient" echo "Email sent to $recipient"
Dry Run
Let's trace sending a notification email with message 'Hello, this is a notification from your script.'
Set variables
message='Hello, this is a notification from your script.' subject='Notification' recipient='user@example.com'
Send email
echo "$message" | mail -s "$subject" "$recipient"
Print confirmation
echo 'Email sent to user@example.com'
| Step | Action | Value |
|---|---|---|
| 1 | Set message | Hello, this is a notification from your script. |
| 1 | Set subject | Notification |
| 1 | Set recipient | user@example.com |
| 2 | Send email command | echo "$message" | mail -s "$subject" "$recipient" |
| 3 | Print output | Email sent to user@example.com |
Why This Works
Step 1: Prepare message and details
The script stores the email message, subject, and recipient in variables for easy reuse and clarity.
Step 2: Send email using mail command
The mail command sends the email; the message is piped into it, and the subject and recipient are specified with options.
Step 3: Confirm email sent
A simple echo statement confirms the script ran and attempted to send the email.
Alternative Approaches
#!/bin/bash recipient="user@example.com" subject="Notification" message="Hello from sendmail!" sendmail $recipient <<EOF Subject: $subject $message EOF echo "Email sent using sendmail to $recipient"
#!/bin/bash message="Hello from mailx!" subject="Notification" recipient="user@example.com" echo "$message" | mailx -s "$subject" "$recipient" echo "Email sent using mailx to $recipient"
Complexity: O(1) time, O(1) space
Time Complexity
Sending an email is a single operation with no loops, so it runs in constant time.
Space Complexity
The script uses a fixed amount of memory for variables and pipes, so space is constant.
Which Approach is Fastest?
All methods run in constant time; differences depend on system mail setup, not script complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| mail command | O(1) | O(1) | Simple email notifications |
| sendmail command | O(1) | O(1) | Advanced email formatting |
| mailx command | O(1) | O(1) | Enhanced mail features |