如何通过C#代码下载Gmail邮件内嵌图片 处理登录验证及重定向问题
根因说明
你原有代码失效的核心原因是Google早已禁用了账号密码直接进行API/资源访问的验证方式,NetworkCredential仅适用于HTTP基本认证、NTLM这类传统验证场景,完全不兼容Google的OAuth2身份校验体系,因此凭证会被直接忽略。
方案1:通过Gmail API直接获取内嵌图片(推荐)
不需要处理URL重定向和独立的认证逻辑,直接通过官方API读取邮件资源,稳定性最高。
操作步骤
- 前往Google Cloud控制台创建项目,启用Gmail API,创建桌面应用类型的OAuth2凭证,将生成的
credentials.json文件放入项目目录,设置为「如果较新则复制」到输出目录。 - 安装所需NuGet包:
Install-Package Google.Apis.Gmail.v1 Install-Package Google.Apis.Auth.Win
- 示例代码:
using Google.Apis.Auth.OAuth2; using Google.Apis.Gmail.v1; using Google.Apis.Services; using Google.Apis.Util.Store; using System.IO; using System.Threading; // 认证逻辑 string[] scopes = { GmailService.Scope.GmailReadonly }; string credPath = "token_store"; UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.FromFile("credentials.json").Secrets, scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; // 创建Gmail服务实例 var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Gmail Image Downloader", }); // 替换为你的邮件ID和内嵌图片的附件ID string messageId = "目标邮件ID"; string attachmentId = "内嵌图片对应的附件ID"; var attachment = service.Users.Messages.Attachments.Get("me", messageId, attachmentId).Execute(); // 解码base64得到图片字节流 byte[] imageBytes = System.Convert.FromBase64String(attachment.Data.Replace('-', '+').Replace('_', '/')); File.WriteAllBytes("Yoda.png", imageBytes);
方案2:直接请求原始图片URL
如果必须使用你拿到的mail.google.com开头的图片URL,可将OAuth2获取的Access Token加入请求头完成验证:
// 复用方案1中拿到的credential对象,获取当前有效Access Token await credential.RefreshTokenAsync(CancellationToken.None); string accessToken = credential.Token.AccessToken; // 构造请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(originalImageUrl); request.AllowAutoRedirect = true; // 加入Bearer认证头 request.Headers.Add("Authorization", $"Bearer {accessToken}"); using HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using Stream stream = response.GetResponseStream(); using FileStream fs = new FileStream("Yoda.png", FileMode.Create); stream.CopyTo(fs);
关于更新疑问的说明
ggpht.com是Google的统一用户内容存储域名,没有公开的独立API可以直接访问该域名下的资源,所有资源访问都需要通过所属的上层服务API(如Gmail、Google Photos等)进行权限校验和资源获取,不需要单独寻找存储服务的API。
内容的提问来源于stack exchange,提问作者DreamingOfSleep
相关产品推荐
相关产品推荐

