c# - 使用 .NET api for Gmail 阅读大尺寸电子邮件

标签 c# gmail-api google-api-dotnet-client google-workspace

我正在尝试使用 Gmail API 获取邮件。我能够获取较小的消息。但是当尝试获取大尺寸消息时,它会抛出异常,因为“任务已取消”。 根据谷歌 documentation我试图以 RAW 和 FULL 格式获取消息。我也尝试增加请求超时。 但结果相同。

有没有其他方法可以阅读大邮件?

这是我的示例代码:

try 
{
    GmailServiceObj = new GmailService(new BaseClientService.Initializer()
                                {
                                    ApplicationName = _appname,
                                    HttpClientInitializer = _userCredentials
                                }); 
    UsersResource.MessagesResource.GetRequest MessageGetRequestObj;
    MessageGetRequestObj= GmailServiceObj.Users.Messages.Get(UserEmailID, ItemID);        
    MessageGetRequestObj.Service.HttpClient.Timeout = new TimeSpan(0, 5, 0);        
    MessageGetRequestObj.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;        
    var _message = MessageGetRequestObj.Execute(); // throws exception
}
catch(Exception e)
{   //The request was aborted: The request was canceled.
    // trying to read same message in parts
    MessageGetRequestObj.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
    var _message = MessageGetRequestObj.Execute();
    string res = Readparts(Emailobj.Payload.Parts, ItemID);

}

private String Readparts(IList<MessagePart> parts, string msgid)
{
    StringBuilder mime = new StringBuilder();
    try
    {
        foreach (var part in parts)
        {

            try
            {
                if (part != null && part.Body != null)
                    mime.Append(part.Body.Data);
                if (part.Body != null && part.Body.AttachmentId != null)
                {
                    var resource = GmailServiceObj.Users.Messages.Attachments.Get("me", msgid, part.Body.AttachmentId);
                    MessagePartBody attachPart = resource.Execute(); // Throws exception 

                    // Converting from RFC 4648 base64 to base64url encoding
                    // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
                    String attachData = attachPart.Data.Replace('-', '+');
                    attachData = attachData.Replace('_', '/');
                    mime.Append(attachData);
                }
                if (part.Parts != null && part.Parts.Count > 0)
                {
                    mime.Append(Readparts(part.Parts, msgid));
                }
            }
            catch (Exception er) { }
        }
    }
    catch (Exception ex)
    {}
    return mime.ToString();
}

提前致谢。

编辑:完成日志

-----------------------------------------------------------------------------------------MAIN EXEPTION------------------------------------------------

Error while copying content to a stream.

at System.Net.Http.HttpContent.d__49.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.HttpClient.d__58.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Google.Apis.Requests.ClientServiceRequest1.<ExecuteUnparsedAsync>d__33.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Google.Apis.Requests.ClientServiceRequest1.Execute()

-----------------------------------------------------------------------------------------INNER EXEPTION------------------------------------------------

Received an unexpected EOF or 0 bytes from the transport stream.

at System.Net.GZipWrapperStream.EndRead(IAsyncResult asyncResult)
at System.IO.Stream.<>c.b__43_1(Stream stream, IAsyncResult asyncResult) at System.Threading.Tasks.TaskFactory1.FromAsyncTrimPromise1.Complete(TInstance thisRef, Func`3 endMethod, IAsyncResult asyncResult, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.IO.Stream.d__27.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.StreamToStreamCopy.<>c.b__1_0(Task completed, Object innerSource) at System.Threading.Tasks.ContinuationTaskFromTask.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.HttpContent.d__49.MoveNext()

最佳答案

MessageGetRequestObj.Service.HttpClient.Timeout = new TimeSpan(0, 5, 0);

这可能是您的问题。看起来您正在将 HTTP 客户端设置为在 5(秒?)不活动后超时。您应该显着增加该超时或完全禁用超时。

关于c# - 使用 .NET api for Gmail 阅读大尺寸电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53423977/

相关文章:

C# 一个项目可以有多个 .config 文件吗?

go - Gmail API在发送电子邮件时忽略 “FROM” header

google-api - Java 版 gmail API 的一部分是否缺失?

oauth-2.0 - 如何使用 Gmail REST API 发送电子邮件

c# - 请求中的重定向 URI : http://localhost:12349/authorize/did not match a registered redirect URI

c# - 是否可以使用 json key 而不是 p12 key 来获取服务帐户凭据?

c# - 如何在 Linux 上使用 Mono 获取文件信息

c# - Vista、Office Interop 不工作

c# - Linq to XML Descendants 和 Elements 之间有什么区别

c# - NativeApplicationClient 和 OAuth2Authenticator 未解析