Azure环境下使用Twilio SendGrid发送邮件时出现「请求方IP地址未在白名单中」错误的求助
解决Azure DevOps中调用SendGrid API的IP白名单错误
问题场景
我在Azure DevOps发布管道中使用Azure PowerShell任务执行以下脚本,调用Twilio SendGrid服务发送邮件:
#region variables param( [Parameter(Mandatory = $true)] [string] $sendGridApiKey, [Parameter(Mandatory = $true)] [string] $toEmailAddress, [Parameter(Mandatory = $true)] [string] $ccEmailAddress ) #endregion #region MainScript #****************************************************************************** # Script body # Execution begins here #****************************************************************************** $ErrorActionPreference = "Stop" $sub = "Test Environment Details" $bodyHtml = "<html> <head> <style> table { border-collapse: collapse; border: 1px solid #dddddd; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } </style> </head> <body style='color: #000000; background-color: #ffffff; font-size: 20px; font-family: Arial, Helvetica, sans-serif'> Dear Developers Team, <p>Your request for creating the resources was completed.</p> <p>Test Environment Details:</p> <p style='white-space:pre;word-wrap: break-word;overflow: hidden;'></p> <p>Thank you </br> Your DevopsTeam</p> </body> </html>" # Create a body for sendgrid $Body = @{ "personalizations" = @( @{ "to" = @( @{ "email" = $toEmailAddress } ) "cc" = @( @{ "email" = $ccEmailAddress } ) "subject" = $sub } ) "content" = @( @{ "type" = "text/html" "value" = $bodyHtml } ) "from" = @{ "email" = "support@xyz.com" } } $BodyJson = $Body | ConvertTo-Json -Depth 4 #Header for SendGrid API $Header = @{ "authorization" = "Bearer $sendGridApiKey" } #Send the email through SendGrid API $Parameters = @{ Method = "POST" Uri = "https://api.sendgrid.com/v3/mail/send" Headers = $Header ContentType = "application/json" Body = $BodyJson } Invoke-RestMethod @Parameters #endregion
但每次执行都会收到错误:
The requestor IP address is not whitelisted
备注:我已在SendGrid中创建了拥有完全权限的API密钥,并在上述脚本中使用了该密钥。
解决方案
这个错误的核心原因是你的SendGrid API密钥(或账户全局)设置了IP白名单限制,而Azure DevOps代理的出口IP不在允许范围内,下面是具体的解决步骤:
1. 检查SendGrid API密钥的IP白名单配置
登录SendGrid管理后台,依次进入 Settings > API Keys,找到你使用的那枚全权限API密钥:
- 点击密钥名称进入编辑页面
- 查看Access Restrictions下的IP Whitelist部分,如果这里有配置IP/IP段,说明只有这些IP能调用该密钥
2. 获取Azure DevOps代理的出口IP
根据你使用的代理类型,获取对应的出口IP:
- Microsoft托管代理:这类代理的出口IP是动态的,你需要找到管道运行区域对应的托管代理IP范围(可在Azure DevOps官方文档中查询对应区域的IP列表)
- 自托管代理:在代理服务器上运行以下PowerShell命令获取公网出口IP:
Invoke-RestMethod https://api.ipify.org
3. 将代理IP/IP范围添加到SendGrid白名单
回到SendGrid的API密钥编辑页面,在IP Whitelist中添加你获取到的IP或IP段:
- 如果是Microsoft托管代理,记得添加对应区域的全部IP段(因为托管代理会随机使用该区域内的IP)
- 保存修改后的API密钥配置
4. 检查SendGrid账户的全局IP访问限制(可选)
部分SendGrid账户可能设置了全局IP限制,进入 Settings > IP Access Management,确认Azure DevOps代理的IP也在全局白名单中(如果这里有配置的话)
5. 可选:关闭IP白名单(不推荐)
如果你的场景无法固定IP或添加大量IP段,可以临时关闭API密钥的IP白名单限制,但这会降低密钥的安全性,仅建议在测试环境使用。
完成以上配置后,重新运行Azure DevOps发布管道,应该就能正常调用SendGrid API发送邮件了。
内容的提问来源于stack exchange,提问作者Pradeep
相关产品推荐
相关产品推荐

