如何在Bash中使用mail命令发送带变量的HTML格式邮件?
解决HTML邮件模板变量不解析、标签不生效的问题
问题描述
原本用printf直接构造纯文本邮件能正常发送,换成读取本地HTML模板文件后出现两个问题:
- 模板里的
$i、$site、$code变量被当作纯文本输出,没被shell解析替换 - 模板中的HTML标签(比如
<bold>)不被邮件客户端识别,格式混乱
原因分析
- 变量未解析:用
template=$(cat ./mail_template)读取模板时,只是把内容存成原始字符串,shell不会自动解析字符串里的变量;用反引号template=cat ./mail_template``的语法更容易出错,同样没法自动解析变量。 - HTML格式无效:模板缺少完整的HTML文档结构(比如
<html>、<body>标签),而且<bold>不是标准HTML标签(标准是<b>或<strong>),纯文本的换行会被HTML忽略,不会显示成换行。
解决方案
1. 正确解析模板变量
推荐用envsubst工具替换变量(比eval安全,避免代码注入风险),指定要替换的变量列表,确保只替换目标变量:
# 读取模板内容 template=$(cat ./mail_template) # 替换指定变量后发送HTML邮件 printf "%s" "$template" | envsubst '$i $site $code' | mail -a 'Content-Type: text/html; charset=utf-8' -s "Urgent notice from $site" "$email" -r "$mail_from"
如果模板里没有其他$开头的非变量字符,也可以直接用printf解析:
template=$(cat ./mail_template) printf "$template" | mail -a 'Content-Type: text/html; charset=utf-8' -s "Urgent notice from $site" "$email" -r "$mail_from"
2. 修复HTML模板结构
把模板改成标准HTML格式,添加必要标签,替换无效标签,用HTML标签控制换行和格式:
<html> <head> <meta charset="utf-8"> </head> <body> <p>Dear $i,</p> <p>Please enable 2FA on $site. This is very important to protect your identity.</p> <p>Your initial code for logging in to your account the next time:</p> <p><strong>$code</strong></p> <p>For detailed instructions please visit: <a href="https://docs.nextcloud.com/server/latest/user_manual/en/user_2fa.html">Nextcloud 2FA Setup Guide</a> </p> <p>You must complete the above steps from instructions, otherwise you will not be able to log into your account a second time!</p> <p>In short you need to do the following steps:</p> <ol> <li>Log in to your account on $site using the above code</li> <li>Enable 2FA as shown in the instructions (link above)</li> <li>Enable security tokens as shown in instructions (link above)</li> </ol> <p><strong>Attention!!!</strong></p> <p>Don't save security tokens to your Nextcloud File Storage. Put them in another safe (preferably encrypted) place, or print them out and store them in a vault.</p> <p>Regards - Your Site Administrator from $site</p> </body> </html>
3. 额外注意事项
- 邮件的
Content-Type要指定charset=utf-8,避免中文或特殊字符乱码 - 确保
$i、$site、$code、$email、$mail_from这些变量在脚本里已经正确定义并赋值 - 如果系统没装
envsubst,可以安装gettext包获取(比如Debian/Ubuntu:sudo apt install gettext)
内容的提问来源于stack exchange,提问作者toddehb
相关产品推荐
相关产品推荐

