可恢复上传使用Google Mail API抛出异常:“错误请求”

时间:2017-07-07 13:09:12

标签: c#-4.0 google-api gmail

我正在尝试使用GMail API将邮件插入Google Mailbox。 我想上传大小超过5 MB的邮件。所以我正在使用Resumable上传请求。

我首先使用 POST 请求启动可恢复上传,并提供“ 200 OK ”响应。

张贴申请:

String postUrl = "https://www.googleapis.com/upload/gmail/v1/users/" + "<username>" + "/messages/send?uploadType=resumable";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest.Headers["Authorization"] = "Bearer " + f_token;// AccessToken;
httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
httpRequest.Headers["X-Upload-Content-Length"] = f_bytes.Length.ToString();
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
var response = (HttpWebResponse)httpRequest.GetResponse(); // 200 OK

根据该回复,我获得了上传EML的位置网址。

位置: https://www.googleapis.com/upload/gmail/v1/users/ / messages / send?uploadType = resumable&amp; upload_id = AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw

要上传EML文件,我使用位置URL作为PUT URL来创建请求。

putUrl = https://www.googleapis.com/upload/gmail/v1/users/<username>/messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw";
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = f_bytes.Length;
int EndOffset = f_bytes.Length;//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + 0 + "-" + EndOffset + "/" + f_bytes.Length;
httpRequest1.ContentType = "message/rfc822";

MemoryStream stream = new MemoryStream(f_bytes);

System.IO.Stream requestStream = httpRequest1.GetRequestStream();
{
                            stream.CopyTo(requestStream);
                            requestStream.Flush();
                            requestStream.Close();
}

HttpWebResponse f_webResponse = (HttpWebResponse)httpRequest1.GetResponse(); //Exception

例外:

  

远程服务器返回错误:(400)错误请求。

请建议soluion将eml文件上传到邮箱的特定文件夹

1 个答案:

答案 0 :(得分:0)

我可以使用可恢复的上传来发送邮件。

if (f_MailService == null)
{
     bool isCreated = createMailService(ref f_MailService);
}
FileStream fs = new FileStream(@p_EMLPath, FileMode.Open,FileAccess.Read);

创建HTTPRequest以发送邮件:

string postUrl = "https://www.googleapis.com/upload/gmail/v1/users/ab@edu.cloudcodes.com/messages/send?uploadType=resumable";

HttpWebRequest f_httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
f_httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
f_httpRequest.Headers["X-Upload-Content-Length"] = fs.Length.ToString();

f_httpRequest.Headers["Authorization"] = "Bearer " + f_token;
f_httpRequest.Method = "POST";
//f_httpRequest.ContentLength = 524288;
f_httpRequest.ContentType = "application/json; charset=UTF-8";//"message/rfc822";
f_httpRequest.ContentLength = fs.Length;
f_httpRequest.Timeout = 6000000;
f_httpRequest.SendChunked = true;

获取第一个POST请求的响应:

try
{
    using (Stream f_ObjHttpStream = f_httpRequest.GetRequestStream())
    {

    }
}
catch (Exception EX)
{

}


try
{
    using (var response = (HttpWebResponse)f_httpRequest.GetResponse())
    {
       // data = ReadResponse(response);
        UploadUrl = response.Headers["Location"].ToString();                             

    }
}
catch (WebException exception)
{
    using (var response = (HttpWebResponse)exception.Response)
    {
       // data = ReadResponse(response);
    }
}

阅读EML文件&amp;发送块数据上传

byte[] Arrbyte = new byte[1024];
int ReadByte = 0;

while (fs.Length > ReadByte)
{
    bool ac = false;
    int ByteRead = 0;
    byte[] Data = new byte[4194304];
    byte[] LastData;
   //Read block of bytes from stream into the byte array
   // if (ReadByte == 0)
    {
        ByteRead = fs.Read(Data, 0, Data.Length);
    }
    //else
    {
        if ((ReadByte + Data.Length) > fs.Length)
        {
            //fs.Length - ReadByte-
            LastData = new byte[fs.Length - ReadByte];
            ByteRead = fs.Read(LastData, 0, LastData.Length);
            CallPUTReq(fs.Length, LastData);
            ac = true;
        }

    }
   //f_MsgRawStr = Convert.ToBase64String(f_bytes).TrimEnd(padding).Replace('+', '-').Replace('/', '_');
   ReadByte = ReadByte + ByteRead;
   if (ac == false)
   {
       CallPUTReq(fs.Length, Data);
   }
   //long pos = fs.Seek(0, SeekOrigin.Current );
   //fs.Position = ReadByte;
}

private void CallPUTReq(long p_lenth, byte[] Arrbyte)
{
    try
    {
        String postUrl = UploadUrl; //"https://www.googleapis.com/upload/gmail/v1/users/ab@edu.cloudcodes.com/messages/send?uploadType=resumable&upload_id=AEnB2UqZNtZVwWulAOhAVoFp-pZ-vTMcIXOpt_0dH_6jJecpm2Y1MNOGkE6JoDb0kn9Dt4yuHHMZWR--dBncxWQkZctF9h6jiPSL5uJDKeYE9Ut1c7-fImc";
        int EndOffset = 0;
        HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
        httpRequest1.Method = "PUT";
        httpRequest1.ContentLength = Arrbyte.Length;
        if (rangeStartOffset == 0)
        {
            EndOffset = Arrbyte.Length - 1;
        }
        else
        {
            EndOffset = rangeStartOffset + Arrbyte.Length - 1;
            if (EndOffset > p_lenth)
            {

                EndOffset = Convert.ToInt32(p_lenth);
                httpRequest1.ContentLength = EndOffset - rangeStartOffset;
            }

        }//5120000;5242880
        httpRequest1.Headers["Content-Range"] = "bytes " + rangeStartOffset + "-" + EndOffset + "/" + p_lenth; //"bytes */" + p_lenth; //
        httpRequest1.ContentType = "message/rfc822";
        httpRequest1.Timeout = 6000000;

        UTF8Encoding encoding = new UTF8Encoding();
        Stream stream = httpRequest1.GetRequestStream();
        stream.Write(Arrbyte, 0, Arrbyte.Length);
        stream.Close();

        try
        {
            using (Stream f_ObjHttpStream = httpRequest1.GetRequestStream())
            {

            }
        }
        catch (Exception EX)
        {

        }
        WebResponse response1 = null;
        try
        {
            using (response1 = (HttpWebResponse)httpRequest1.GetResponse())
            {

            }
        }
        catch (Exception ex)
        {

           // UploadUrl = response1.Headers["Location"].ToString();
        }
        //4194303
        rangeStartOffset = EndOffset +1;
    }
    catch (Exception)
    {

    }
}