我只想用ASP.NET MVC以编程方式下载上一封电子邮件中的附件。
据我所知,Google需要的唯一权限是“https://www.googleapis.com/auth/gmail.readonly”授予我“读取所有资源及其元数据 - 无需写入操作”。资源: (https://developers.google.com/gmail/api/auth/scopes)
问题是当我尝试访问附件时出现错误:
$exception
{"Google.Apis.Requests.RequestError
Invalid attachment token [400]
Errors
[Message[Invalid attachment token]
Location[ - ] Reason[invalidArgument]
Domain[global]\r\n]\r\n"}
到目前为止,这是我的代码示例:
static string[] Scopes = { GmailService.Scope.GmailReadonly };
public ActionResult Login()
{
UserCredential credential;
var diskPath = Server.MapPath("~");
using (var stream = new FileStream(diskPath + "/Content/client_secret.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None).Result;
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var resp = service.HttpClient.GetStringAsync("https://www.googleapis.com/gmail/v1/users/me/messages?q=\"has:attachment\"").Result;
var root = JsonConvert.DeserializeObject<ListMessagesResponse>(resp);
foreach (var msg in root.Messages)
GetAttachments(service, msg.Id);
return View();
}
public static void GetAttachments(GmailService service, String messageId)
{
var message = service.Users.Messages.Get("me", messageId).Execute();
var parts = message.Payload.Parts;
foreach (var part in parts)
{
if (!String.IsNullOrEmpty(part.Filename))
{
var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
var file = Convert.FromBase64String(attachPart.Data);
System.IO.File.WriteAllBytes(part.Filename, file);
}
}
}
我通过时遇到此错误:
var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
我还需要为附件添加任何其他范围吗?或者我必须在一些操作后刷新令牌?我已经尝试删除并在我的Google+个人资料中再次添加该应用程序了!
答案 0 :(得分:1)
[我的错误]
而不是:
var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
我必须使用这样的ATTACHMENT ID:
var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.Body.AttachmentId).Execute();