使用 HttpClient 获取 Gmail Atom Feed

Getting Gmail Atom Feed with HttpClient

我正在尝试使用 HttpClient 获取电子邮件帐户的 Atom 提要。在我尝试获取 mail.google.com 并将它们与自定义 HttpClientHandler 一起使用之前,但它没有用。

我搜索了解决方案并设法发现我可以使用 `Authorization header 将凭据传递到服务器,但这也不起作用。难道我做错了什么?为什么我会收到 401 错误?这个方法行不通了?

这是我的代码:

public async Task<bool> CheckMail()
{
    AMailRefresher.handler.CookieContainer = new CookieContainer();
    string url = "https://mail.google.com/mail/feed/atom";
    var encoded = StringToByte64(user + ":" + password);
    HttpResponseMessage res = null;
    try
    {
        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, url);
        req.Headers.Add("Authorization", "Basic " + encoded);
        res = await AMailRefresher.http.SendAsync(req);
    }
    catch { }
    var xml = await res.Content.ReadAsStringAsync();
    if (lastFeedScan == null)
        lastFeedScan = xml;
    if (xml != lastFeedScan)
    {
        lastFeedScan = xml;
        return true;
    }
    return false;
}

private static string StringToByte64(string text)
{
    ASCIIEncoding encoding = new ASCIIEncoding();
    var bytes = encoding.GetBytes(text);
    return Convert.ToBase64String(bytes, 0, bytes.Length);
}

如果您启用了 2-Step Verification for your Google account (i.e. new logins send a code in a text message to your phone which you must then enter to authorize the login) then you cannot use your (base 64 encoded) normal password with this approach. Instead, you must create an App password in order to bypass the 2-Step Verification. See Sign in using App Passwords for detail. The How to generate an App password section directs you to App passwords,您可以在其中创建一个自定义的、唯一的 16 个字符的密码供您的应用程序使用。