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

使用Curl发送带附件邮件报错:非法格式输入字段

问题

我用Curl发送带附件的邮件,在Ubuntu 20.04.4上能正常运行,但在Ubuntu 16.04.7上出现以下错误:

Warning: Illegally formatted input field
curl: option --form: is badly used here

对应的脚本代码:

attachmentFileWithPath="aa/test.log"
attachmentType="$(file --mime-type "$attachmentFileWithPath" | sed 's/.*: //')"
server='smtp.aa.com'
port='587'
user='donotreply@gmail.com'
pass='aaa'
senderAddress="$user"
subject="subject"
mailBody="mail body"

curl --ssl-reqd --url "smtp://$server:$port" \
--user "$user:$pass" \
--mail-from "$senderAddress" \
--mail-rcpt "abc@gmail.com" \
--mail-rcpt "abc1@gmail.com" \
--header "From: donotreply <$senderAddress>" \
--header "To: abc <abc@gmail.com>" \
--header "To: abc1 <abc1@gmail.com>" \
--header "Subject: $subject" \
--form '=(;type=multipart/mixed' --form "=$mailBody;type=text/plain" \
--form "file=@$attachmentFileWithPath;type=$attachmentType;encoder=base64" --form '=)'
原因

Ubuntu 16.04.7默认搭载的curl版本为7.47.0,而Ubuntu 20.04.4使用的是7.68.0左右的新版本。你脚本里用--form配合=(;type=multipart/mixed、=)这种语法构造多附件邮件的方式,是curl 7.56.0之后才新增的功能,旧版本curl不识别该写法,因此报错。

解决办法

办法1:升级Ubuntu 16.04上的curl版本

通过官方PPA将curl升级到支持该语法的版本:

sudo add-apt-repository ppa:curl/curl
sudo apt update
sudo apt install curl

升级完成后重新运行原脚本即可。

办法2:使用兼容旧版本curl的写法

手动构造符合MIME规范的邮件内容,通过--upload-file参数传递给curl,无需依赖新版本的--form语法。修改后的脚本如下:

attachmentFileWithPath="aa/test.log"
attachmentType="$(file --mime-type "$attachmentFileWithPath" | sed 's/.*: //')"
server='smtp.aa.com'
port='587'
user='donotreply@gmail.com'
pass='aaa'
senderAddress="$user"
subject="subject"
mailBody="mail body"

# 生成随机的MIME边界字符串
boundary="----$(date +%s%N)"

# 创建临时文件存储邮件内容
temp_mail=$(mktemp)

# 写入邮件头部和多部分内容
cat > "$temp_mail" <<EOF
From: donotreply <$senderAddress>
To: abc <abc@gmail.com>, abc1 <abc1@gmail.com>
Subject: $subject
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="$boundary"

--$boundary
Content-Type: text/plain; charset=utf-8

$mailBody

--$boundary
Content-Type: $attachmentType
Content-Disposition: attachment; filename="$(basename "$attachmentFileWithPath")"
Content-Transfer-Encoding: base64

$(base64 -w 0 "$attachmentFileWithPath")

--$boundary--
EOF

# 发送邮件
curl --ssl-reqd --url "smtp://$server:$port" \
--user "$user:$pass" \
--mail-from "$senderAddress" \
--mail-rcpt "abc@gmail.com" \
--mail-rcpt "abc1@gmail.com" \
--upload-file "$temp_mail"

# 清理临时文件
rm "$temp_mail"

这个脚本手动处理了MIME多部分邮件的构造和附件的base64编码,兼容所有版本的curl。

内容的提问来源于stack exchange,提问作者Nitin Alety

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:06:05