首页 > 解决方案 > 尝试将 json 作为电子邮件信息发送到 api(Sendgrid) 时出现 400 BAD REQUEST 错误

问题描述

我有一个程序,最后一步是向多个客户发送电子邮件。制作一个 excel 文件作为附件发送这些电子邮件。我使用 sendgrid 提供的 api 发送电子邮件。但是,当触发 getresponse 阶段时出现异常:“400 bad request”。我尝试使用邮递员检查 api 密钥和 url 的有效性。它在那里成功,所以我认为我的 json 转换/语法可能不正确。我不确定,我大约一个月前才开始使用 Visual Basic。

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

            Dim attachmentpath As String = strAppPath & strFileCompleteDir
            Dim uri As String = "URL"
            Dim Request As WebRequest = WebRequest.CreateHttp(uri)
            Request.Method = "POST"
            Request.PreAuthenticate = True
            Request.Headers.Add("Authorization", "Bearer 'API_KEY'")
         

            Dim json_data As String = "{'personalizations': [{'To': [{'email': ''To_email''}]}],'from': {'email': 'From_email'},'subject': '[encrypt]Hello, World! test','content': [{'type': 'text/plain', 'value': 'Heya!'}]}"

            Request.ContentType = "application/json"
            Dim json_bytes() As Byte = Encoding.UTF8.GetBytes(json_data)
            Request.ContentLength = json_bytes.Length


            Using requeststream = Request.GetRequestStream
                requeststream.Write(json_bytes, 0, json_bytes.Length)
            End Using

            Dim responsecontent As String = Nothing
            Using Response = DirectCast(Request.GetResponse, HttpWebResponse),
                    responseStream = Response.GetResponseStream()
                Using reader = New StreamReader(responseStream)
                    responsecontent = reader.ReadToEnd()
                End Using
            End Using
 

标签: jsonvb.netsendgrid

解决方案


推荐阅读