我正在为 Windows Store 应用程序编写课程,该应用程序可以连接到 imap.gmail.com、查找特定消息并从中下载电子邮件附件。我决定编写自己的课程,因为找不到任何适用于 Windows 应用商店的现成解决方案。
即使连接 imap 服务器也有问题,我使用 StreamSocket 并且无法理解,我做错了什么。这是我的代码:
public sealed class GmailAttachmentDownloader
{
private HostName HostName;
private StreamSocket Socket;
private String AccessToken;
private String LoginName;
private DataWriter Writer;
private DataReader Reader;
public GmailAttachmentDownloader(String loginName, String accessToken)
{
HostName = new HostName("imap.gmail.com");
LoginName = loginName;
AccessToken = accessToken;
}
private async Task<bool> Connect()
{
Socket = new StreamSocket();
try
{
await Socket.ConnectAsync(HostName, "993", SocketProtectionLevel.SslAllowNullEncryption);
}
catch
{
return false;
}
return true;
}
private async Task<bool> Write(String msg)
{
if (Socket == null)
if (! await Connect())
throw new Exception("Could not connect to imap.gmail.com");
try {
using (Writer = new DataWriter(Socket.OutputStream))
{
Writer.WriteString(msg);
await Writer.StoreAsync();
}
}
catch
{
return false;
}
return true;
}
private async Task<String> Read()
{
if (Socket == null)
if (!await Connect())
throw new Exception("Could not connect to imap.gmail.com");
String data;
using(Reader = new DataReader(Socket.InputStream))
{
Reader.InputStreamOptions = InputStreamOptions.Partial;
await Reader.LoadAsync(1024);
data = Reader.ReadString(Reader.UnconsumedBufferLength);
}
return data;
}
public async void Login()
{
String data;
data = await Read();
await Write("a1 AUTHENTCATE XOAUTH2 " + EncodeTo64("user=" + LoginName + "\x01auth=Bearer " + AccessToken + "\x01\x01\r\n"));
data = await Read();
}
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.UTF8Encoding.UTF8.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= System.Convert.FromBase64String(encodedData);
string returnValue =
System.Text.UTF8Encoding.UTF8.GetString(encodedDataAsBytes, 0, encodedDataAsBytes.Count());
return returnValue;
}
}
有人可以帮我吗?我尝试在网络和微软教程中搜索,我也发现了这个问题,但它对我没有多大帮助。
UPD:对不起,我在谷歌搜索异常后,发现问题出在杀毒软件中,当我关闭杀毒软件后一切正常。如此不同的问题:如何处理它?我不想告诉我的朋友“关闭你的杀毒软件,这样我的程序才能运行”?