使用Gmail API下载零字节附件

时间:2015-09-07 20:01:51

标签: .net vb.net gmail-api

我有一些包含空文件附件的邮件,我无法下载,因为Gmail API没有分配AttachmentId。鉴于已经设计好的流程,我需要下载这些文件并保存它们,即使它们是空的。

获取附件的代码取自Gmail API,已翻译为vb.net并稍加修改:

Try
Dim message As Google.Apis.Gmail.v1.Data.Message = service.Users.Messages.Get(userId, messageId).Execute()
Dim parts As IList(Of Google.Apis.Gmail.v1.Data.MessagePart) = message.Payload.Parts

For Each part As Google.Apis.Gmail.v1.Data.MessagePart In parts
    If Not String.IsNullOrEmpty(part.Filename) And Regex.IsMatch(part.Filename, searchedFile) And Not part.Body.AttachmentId Is Nothing Then
        Dim attId As String = part.Body.AttachmentId
        Dim attachPart As Google.Apis.Gmail.v1.Data.MessagePartBody = service.Users.Messages.Attachments.Get(userId, messageId, attId).Execute()

        ' Converting from RFC 4648 base64-encoding
        ' see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
        Dim attachData As String = attachPart.Data.Replace("-", "+")
        attachData = attachData.Replace("_", "/")

        Dim data As Byte() = Convert.FromBase64CharArray(attachData, 0, attachData.Length)

        If Not Directory.Exists(outputDir) Then
            Directory.CreateDirectory(outputDir)
        End If

        File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data)

    End If
Next

Catch ex As Exception
' ErrorHandler(ex)
End Try

有一个Nothing值测试,只是为了避免GoogleApiException。

有没有办法用Gmail API下载空文件?

提前致谢

0 个答案:

没有答案