如何将ssmtp发邮件的终端命令转为Bash脚本执行?
Best Ways to Turn Your ssmtp Command into a Bash Script
Hey there! Since you're new to Bash scripting, let's turn that ssmtp one-liner into a clean, maintainable script. Here are a few optimal approaches, starting from simple to more flexible:
1. Basic Straightforward Script
This is the simplest way—just wrap your existing command in a script file, with a shebang at the top to tell the system it's a Bash script:
#!/bin/bash # Send alert email via ssmtp { echo "To: user@gmail.com" echo "From: user@gmail.com" echo "Subject: [Alert]" echo "McDonalds now offers vegan burgers and vegan ice cream!" } | ssmtp user@gmail.com
How to use:
- Save this as
send_alert.sh - Make it executable:
chmod +x send_alert.sh - Run it:
./send_alert.sh
2. Flexible Script with Variables
If you want to easily change recipients, senders, or the message later, use variables. This makes the script reusable for different scenarios:
#!/bin/bash # Configure email details RECIPIENT="user@gmail.com" SENDER="user@gmail.com" SUBJECT="[Alert]" MESSAGE="McDonalds now offers vegan burgers and vegan ice cream!" # Send the email { echo "To: $RECIPIENT" echo "From: $SENDER" echo "Subject: $SUBJECT" echo "$MESSAGE" } | ssmtp "$RECIPIENT"
3. Using a Here-Document (Cleaner for Multi-Line Messages)
If your message gets longer or has line breaks, a here-document (<<EOF) is much cleaner than multiple echo commands. It preserves formatting too:
#!/bin/bash RECIPIENT="user@gmail.com" SENDER="user@gmail.com" SUBJECT="[Alert]" # Send email using here-doc for the message body ssmtp "$RECIPIENT" <<EOF To: $RECIPIENT From: $SENDER Subject: $SUBJECT McDonalds now offers vegan burgers and vegan ice cream! P.S. This message uses a here-document for cleaner formatting. EOF
Pro Tips:
- Always add the shebang (
#!/bin/bash) at the top—this ensures the script runs with Bash, not another shell. - If you get permission errors, double-check that
ssmtpis installed and your user has access to it. - For more robustness, you could add error checking (e.g., check if
ssmtpexists before running), but that's optional for a basic script.
内容的提问来源于stack exchange,提问作者Daniel Baeriswyl
相关产品推荐
相关产品推荐

