You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 ssmtp is installed and your user has access to it.
  • For more robustness, you could add error checking (e.g., check if ssmtp exists before running), but that's optional for a basic script.

内容的提问来源于stack exchange,提问作者Daniel Baeriswyl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:33:15