如何通过SendGrid的Curl接口在邮件中嵌入图片?
问题:Windows下用SendGrid Curl接口发送带嵌入式图片的邮件失败
我在Windows系统下尝试用SendGrid的Curl接口发送带嵌入式图片(非附件)的邮件,但搞不清正确语法。因为Windows命令行的JSON引号问题,我只能创建文件并用curl的-d参数来传数据。
使用的curl命令
curl --url https://api.sendgrid.com/v3/mail/send --request POST ^ --header "Authorization: Bearer mybearertokenstring " ^ --header "Content-Type: application/json" ^ -d "@E:\temp\curl_RCC_20240506104528.tmp"
注:Windows命令行换行需用^而非\,替换后可避免执行报错
临时文件内容
{"personalizations": [{"to": [{"email": "myemail@domain.com"}]}], "from": {"email": "fromemail@domain.com"}, "subject": "folio number", "content": [{"type": "text/html", "value": "<html><body>Image file = E:/images/allproplogo.jpg<br><img height="326" width="620" id="Picture 2" class="center" src="cid:image0001" /></body></html>"}] ,"files": [{"filename":"allproplogo.jpg", "type": "image/jpeg", "cid":"image0001", "content":"base64encodedimage"}]}
收到的错误信息
{"errors":[{"message":"Bad Request","field":null,"help":null}]}
我试过多种Base64编码组合,但要么收到上述错误,要么出现UTF8格式错误。
解决方案
1. 修正API字段错误
SendGrid v3 API中,嵌入式图片需放在attachments数组中,而非files。同时要给附件设置disposition: "inline",明确这是嵌入式资源而非普通附件。
2. 修复JSON格式问题
HTML字符串中的双引号(如height="326")未转义,会导致JSON解析失败,必须转义为\"。另外,Bearer token末尾不要留空格,否则会触发授权失败。
3. 确保Base64编码正确
用PowerShell生成正确的图片Base64编码(避免手动编码出错):
[Convert]::ToBase64String((Get-Content -Path "E:/images/allproplogo.jpg" -Encoding Byte))
生成的编码需保证是连续无换行的字符串。
修正后的临时文件JSON示例
{ "personalizations": [{"to": [{"email": "myemail@domain.com"}]}], "from": {"email": "fromemail@domain.com"}, "subject": "folio number", "content": [ { "type": "text/html", "value": "<html><body>Image file = E:/images/allproplogo.jpg<br><img height=\"326\" width=\"620\" id=\"Picture 2\" class=\"center\" src=\"cid:image0001\" /></body></html>" } ], "attachments": [ { "filename": "allproplogo.jpg", "type": "image/jpeg", "disposition": "inline", "cid": "image0001", "content": "这里替换成正确的Base64编码字符串" } ] }
修正后的curl命令(Windows版)
curl --url https://api.sendgrid.com/v3/mail/send --request POST ^ --header "Authorization: Bearer mybearertokenstring" ^ --header "Content-Type: application/json" ^ -d "@E:\temp\curl_RCC_20240506104528.tmp"
内容的提问来源于stack exchange,提问作者William Hawkins
相关产品推荐
相关产品推荐

