从 C# 读取 Gmail 帐户的 Atom 提要
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/989986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading Atom feed of gmail account from C#
提问by Crash893
I have a project that will send an email with certain data to a gmail account. I think that it will probably be easier to read the Atom feed rather than connect through POP.
我有一个项目将向 Gmail 帐户发送一封包含某些数据的电子邮件。我认为阅读 Atom 提要可能比通过 POP 连接更容易。
The url that I should be using according to Google is:
根据谷歌,我应该使用的网址是:
https://gmail.google.com/gmail/feed/atom
The question/problem is: how do I authenticate the email account I want to see? If I do it in Firefox, it uses the cookies.
问题/问题是:如何验证我想查看的电子邮件帐户?如果我在 Firefox 中这样做,它会使用 cookie。
I'm also uncertain how exactly to "download" the XML file that this request should return (I believe the proper term is stream).
我也不确定如何“下载”这个请求应该返回的 XML 文件(我相信正确的术语是流)。
Edit 1:
编辑1:
I am using .Net 3.5.
我正在使用 .Net 3.5。
采纳答案by alex
This is what I used in Vb.net:
这是我在 Vb.net 中使用的:
objClient.Credentials = New System.Net.NetworkCredential(username, password)
objClient is of type System.Net.WebClient.
objClient 是 System.Net.WebClient 类型。
You can then get the emails from the feed using something like this:
然后,您可以使用以下内容从提要中获取电子邮件:
Dim nodelist As XmlNodeList
Dim node As XmlNode
Dim response As String
Dim xmlDoc As New XmlDocument
'get emails from gmail
response = Encoding.UTF8.GetString(objClient.DownloadData("https://mail.google.com/mail/feed/atom"))
response = response.Replace("<feed version=""0.3"" xmlns=""http://purl.org/atom/ns#"">", "<feed>")
'Get the number of unread emails
xmlDoc.LoadXml(response)
node = xmlDoc.SelectSingleNode("/feed/fullcount")
mailCount = node.InnerText
nodelist = xmlDoc.SelectNodes("/feed/entry")
node = xmlDoc.SelectSingleNode("title")
This should not be very different in C#.
这在 C# 中应该不会有太大的不同。
回答by Kirtan
.NET framework 3.5 provides native classes to read feeds. Thisarticles describes how to do it.
.NET framework 3.5 提供本机类来读取提要。这篇文章描述了如何做到这一点。
I haven't used it tho, but there must be some provision for authentication to a URL. You can check that out. I too will do it, and post the answer back.
我还没有使用过它,但是必须有一些对 URL 进行身份验证的规定。你可以检查一下。我也会这样做,然后将答案发回。
If you are not using framework 3.5, then you can try Atom.NET. I have used it once, but its old. You can give it a try if it meets your needs.
如果您没有使用框架 3.5,那么您可以尝试Atom.NET。我用过一次,但是很旧。如果它满足您的需求,您可以尝试一下。
EDIT: This is the code for assigning user credentials:
编辑:这是分配用户凭据的代码:
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = new NetworkCredential("[email protected]", "password");
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = resolver;
XmlReader reader = XmlReader.Create("https://gmail.google.com/gmail/feed/atom", settings);
回答by Matthew Flaschen
You use Basic Auth. Basically, you make an initial request, the server replies with 401, and then you send back the password in base64 (in this case over HTTPS).
您使用基本身份验证。基本上,您发出初始请求,服务器回复 401,然后您以 base64(在本例中通过 HTTPS)发回密码。
Note though that:
请注意:
- The feed only allows you to get trivial info about the account (e.g. new mail). It does not allow you to send messages.
- POP can not be used to send messages either.
- Usually SMTP is used, and it really isn't that hard.
- 提要只允许您获取有关帐户的琐碎信息(例如新邮件)。它不允许您发送消息。
- POP 也不能用于发送消息。
- 通常使用 SMTP,它真的没有那么难。
EDIT: Here's an example for authenticating and loading the Atom feed into an XmlDocument. Note though that will only provide read access. Search or ask another question for info on C# and SMTP. The ICertificatePolicy junk was necessary for me as Mono didn't like Google's certificate. It's a quick workaround, not suitable for production.
编辑:这是一个用于验证 Atom 提要并将其加载到 XmlDocument 中的示例。请注意,这只会提供读取访问权限。搜索或提出其他问题以获取有关 C# 和 SMTP 的信息。ICertificatePolicy 垃圾对我来说是必要的,因为 Mono 不喜欢 Google 的证书。这是一个快速的解决方法,不适合生产。
Okay, since you've clarified you're actually reading mail (and a different component is sending it), I recommend you do use POP. :
好的,既然您已经澄清您实际上是在阅读邮件(并且正在发送邮件),我建议您确实使用 POP。:
using System;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
public class GmailFeed
{
private class IgnoreBadCerts : ICertificatePolicy
{
public bool CheckValidationResult (ServicePoint sp,
X509Certificate certificate,
WebRequest request,
int error)
{
return true;
}
}
public static void Main(string[] argv)
{
if(argv.Length != 2)
{
Console.Error.WriteLine("Usage: GmailFeed username password");
Environment.ExitCode = 1;
return;
}
ServicePointManager.CertificatePolicy = new IgnoreBadCerts();
NetworkCredential cred = new NetworkCredential();
cred.UserName = argv[0];
cred.Password = argv[1];
WebRequest req = WebRequest.Create("https://gmail.google.com/gmail/feed/atom");
req.Credentials = cred;
Stream resp = req.GetResponse().GetResponseStream();
XmlReader reader = XmlReader.Create(resp);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
}
}
回答by Gordon McAllister
For what its worth, I have never been able to autheniticate via:
就其价值而言,我从未能够通过以下方式进行身份验证:
https://gmail.google.com/gmail/feed/atom
However I can always authenticate on:
但是我总是可以在以下方面进行身份验证:
https://mail.google.com/mail/feed/atom
HTH!!
哈!!
回答by Vladimir Georgiev
Here is my lean and mean solution:
这是我的精益和卑鄙的解决方案:
public static string TextToBase64(string sAscii)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] bytes = encoding.GetBytes(sAscii);
return System.Convert.ToBase64String(bytes, 0, bytes.Length);
}
public static void foobar()
{
var url = @"https://gmail.google.com/gmail/feed/atom";
var USER = "userName";
var PASS = "password";
var encoded = TextToBase64(USER + ":" + PASS);
var myWebRequest = HttpWebRequest.Create(url);
myWebRequest.Method = "POST";
myWebRequest.ContentLength = 0;
myWebRequest.Headers.Add("Authorization", "Basic " + encoded);
var response = myWebRequest.GetResponse();
var stream = response.GetResponseStream();
// Parse the stream using your favorite parsing library or using XmlDocument ...
}
回答by Brandon
The following method seems to work to check the amount of unread messages. I do not know much about xml at all so I was unable to parse the results other than retrieve the unread count. (Returns -1 on error)
以下方法似乎可以检查未读消息的数量。我对 xml 不太了解,所以除了检索未读计数之外,我无法解析结果。(错误返回-1)
public int GmailUnreadCount(string username, string password)
{
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = new NetworkCredential(username, password);
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = resolver;
try
{
XmlReader reader = XmlReader.Create("https://mail.google.com/mail/feed/atom", settings);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
switch (reader.Name)
{
case "fullcount":
int output;
Int32.TryParse(reader.ReadString(), out output);
return output;
}
break;
}
}
}
catch (Exception a)
{
MessageBox.Show(a.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return -1;
}
return -1;
}