尝试使用GoogleMailSettingsService类imapupdate启用IMAP时出现错误 [英] i got an error when trying to enable IMAP using GoogleMailSettingsService class imapupdate

查看:88
本文介绍了尝试使用GoogleMailSettingsService类imapupdate启用IMAP时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用UpdateImap方法更新imap时.向我退却此错误:

GDataRequestException未处理
请求执行失败: https://apps-apis.google.com/a/feeds/emailsettings/2.0/imap.google.com/Providentinnovation Test/imap

请参见以下代码快照:

when i tring to update the imap using the UpdateImap method. retirn to me this error :

GDataRequestException was unhandled
Execution of request failed: https://apps-apis.google.com/a/feeds/emailsettings/2.0/imap.google.com/Providentinnovation Test/imap

see the below code snapshot:

domain = "www.gmail.com";
 adminEmail = "myemail@gmail.com";
 adminPassword = "********";
 testUserName = "myemail@gmail.com";
 GoogleMailSettingsService service = new GoogleMailSettingsServic(domain, "apps-demo");
service.setUserCredentials(adminEmail, adminPassword);
service.UpdateImap(testUserName, "true");



我收到以下错误:未处理GDataRequestException



i got the below error : GDataRequestException was unhandled

推荐答案



首先确保这正是您要制作的东西? IMAP将电子邮件副本下载到本地计算机,因为POP3可以直接从服务器访问电子邮件.

因此,如果您要开发电子邮件客户端(例如Outlook或Thunderbird),则IMAP是一个不错的选择.在这种情况下,您需要处理将保存在计算机上,然后更新到邮件服务器的电子邮件文件.

如果您只想阅读/发送电子邮件,则应使用POP3.

***********
此外,请确保在您的GMAIL设置中启用了电子邮件转发选项***********

对于POP3,此代码有效:

Hi,

1st make sure that this exactly what you want to make? IMAP download the copy of emails to local machine where as POP3 provides access to emails directly from server.

So if you are trying to develop a email client like outlook or thunderbird IMAP is a good option. in that case you need to handle email files which will be saved on your computer and then updated to your mail server.

if you simply wants to read/send emails you should use POP3.

***********
ALSO MAKE SURE THAT EMAIL FORWARDING OPTION IS ENABLED IN YOUR GMAIL SETTING ***********

For POP3 This code will work:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;  using System.Xml;
namespace Prabhu
{
	public class Pop3Client : IDisposable
	{
		public string Host { get; protected set; }
		public int Port { get; protected set; }
		public string Email { get; protected set; }
		public string Password { get; protected set; }
		public bool IsSecure { get; protected set; }
		public TcpClient Client { get; protected set; }
		public Stream ClientStream { get; protected set; }
		public StreamWriter Writer { get; protected set; }
		public StreamReader Reader { get; protected set; }
		private bool disposed = false;
		public Pop3Client(string host, int port, string email,
		string password): this(host, port, email, password, false){}
		public Pop3Client(string host, int port, string email,
		string password, bool secure)
		{
			Host = host;
			Port = port;
			Email = email;
			Password = password;
			IsSecure = secure;
		}
		public void Connect()
		{
			if (Client == null)
				Client = new TcpClient();
			if (!Client.Connected)
				Client.Connect(Host, Port);
			if (IsSecure)
			{
				SslStream secureStream =
				new SslStream(Client.GetStream());
				secureStream.AuthenticateAsClient(Host);
				ClientStream = secureStream;
				secureStream = null;
			}
			else
				ClientStream = Client.GetStream();
			Writer = new StreamWriter(ClientStream);
			Reader = new StreamReader(ClientStream);
			ReadLine();
			Login();
		}
		public int GetEmailCount()
		{
			int count = 0;
			string response = SendCommand("STAT");
			if (IsResponseOk(response))
			{
				string[] arr = response.Substring(4).Split(' ');
				count = Convert.ToInt32(arr[0]);
			}
			else
				count = -1;
			return count;
		}
		public Email FetchEmail(int emailId)
		{
			if (IsResponseOk(SendCommand("TOP " + emailId + " 0")))
				return new Email(ReadLines());
			else
				return null;
		}
		public List<email> FetchEmailList(int start, int count)
		{
			List<email> emails = new List<email>(count);
			for (int i = start; i < (start + count); i++)
			{
				Email email = FetchEmail(i);
				if (email != null)
					emails.Add(email);
			}
			return emails;
		}
		public List<messagepart> FetchMessageParts(int emailId)
		{
			if (IsResponseOk(SendCommand("RETR " + emailId)))
				return Util.ParseMessageParts(ReadLines());
			return null;
		}
		public void Close()
		{
			if (Client != null)
			{
				if (Client.Connected)
					Logout();
				Client.Close();
				Client = null;
			}
			if (ClientStream != null)
			{
				ClientStream.Close();
				ClientStream = null;
			}
			if (Writer != null)
			{
				Writer.Close();
				Writer = null;
			}
			if (Reader != null)
			{
				Reader.Close();
				Reader = null;
			}
			disposed = true;
		}
		public void Dispose()
		{
			if (!disposed)
				Close();
		}
		protected void Login()
		{
			if (!IsResponseOk(SendCommand("USER " + Email))
			|| !IsResponseOk(SendCommand("PASS " + Password)))
				throw new Exception("User/password not accepted");
		}
		protected void Logout()
		{
			SendCommand("RSET");
		}
		protected string SendCommand(string cmdtext)
		{
			Writer.WriteLine(cmdtext);
			Writer.Flush();
			return ReadLine();
		}
		protected string ReadLine()
		{
			return Reader.ReadLine() + "\r\n";
		}
		protected string ReadLines()
		{
			StringBuilder b = new StringBuilder();
			while (true)
			{
				string temp = ReadLine();
				if (temp == ".\r\n" || temp.IndexOf("-ERR") != -1)
					break;
					b.Append(temp);
			}
			return b.ToString();
		}
		protected static bool IsResponseOk(string response)
		{
			if (response.StartsWith("+OK"))
				return true;
			if (response.StartsWith("-ERR"))
				return false;
			throw new Exception("Cannot understand server response: " +
						response);
		}
	}
	public class Email
	{
		public NameValueCollection Headers { get; protected set; }
		public string ContentType { get; protected set; }
		public DateTime UtcDateTime { get; protected set; }
		public string From { get; protected set; }
		public string To { get; protected set; }
		public string Subject { get; protected set; }
		public Email(string emailText)
		{
			Headers = Util.ParseHeaders(emailText);
			ContentType = Headers["Content-Type"];
			From = Headers["From"];
			To = Headers["To"];
			Subject = Headers["Subject"];
			if (Headers["Date"] != null)
				try
				{
					UtcDateTime =Util.ConvertStrToUtcDateTime
							(Headers["Date"]);
				}
				catch (FormatException)
				{
					UtcDateTime = DateTime.MinValue;
				}
			else
				UtcDateTime = DateTime.MinValue;
		}
	}
	public class MessagePart
	{
		public NameValueCollection Headers { get; protected set; }
		public string ContentType { get; protected set; }
		public string MessageText { get; protected set; }
		public MessagePart(NameValueCollection headers, string messageText)
		{
			Headers = headers;
			ContentType = Headers["Content-Type"];
			MessageText = messageText;
		}
	}
	public class Util
	{
		protected static Regex BoundaryRegex = new Regex("Content-Type:
		multipart(?:/\\S+;)" + "\\s+[^\r\n]*boundary=\"?
		(?<boundary>" + "[^\"\r\n]+)\"?\r\n",
		RegexOptions.IgnoreCase | RegexOptions.Compiled);
		protected static Regex UtcDateTimeRegex = new Regex(@"^(?:\w+,\s+)?
		(?<day>\d+)\s+(?<month>\w+)\s+(?<year>\d+)\s+
		(?<hour>\d{1,2})" + @":(?<minute>\d{1,2}):
		(?<second>\d{1,2})\s+(?<offsetsign>\-|\+)
		(?<offsethours>" + @"\d{2,2})(?<offsetminutes>
		\d{2,2})(?:.*)


",RegexOptions.IgnoreCase | RegexOptions.Compiled); 公共 静态 NameValueCollection ParseHeaders(字符串 headerText) { NameValueCollection标头= NameValueCollection(); StringReader reader = StringReader(headerText); 字符串行; 字符串 headerName = ,headerValue; int ColonIndx; 同时((line = reader.ReadLine())!= ) { 如果(行== " ) break ; 如果(Char.IsLetterOrDigit(line [ 0 ])&& (colonIndx = line.IndexOf(' :'))!= -1) { headerName = line.Substring( 0 ,colonIndx); headerValue = line.Substring (colonIndx + 1 ).Trim(); headers.Add(headerName,headerValue); } 其他 如果(标题名称!= ) headers [headerName] + = " + line.Trim(); 其他 抛出 FormatException (" ); } 返回标题; } 公共 静态列表< messagepart> ParseMessageParts(字符串 emailText) { List< messagepart> messageParts = 列表< messagepart>(); int newLinesIndx = emailText.IndexOf(" ); 匹配m = BoundaryRegex.Match(emailText); 如果(m.Index < emailText.IndexOf(" \ r \ n \ r \ n")&& m.成功) { 字符串 boundary = m.Groups [" span>].Value; 字符串 startingBoundary = " +边界; int startingBoundaryIndx = -1; 同时() { 如果(startingBoundaryIndx == -1) startingBoundaryIndx = emailText.IndexOf(startingBoundary); 如果(startingBoundaryIndx!= -1) { int nextBoundaryIndx = emailText.IndexOf (开始边界, startingBoundaryIndx + startingBoundary.Length); 如果(nextBoundaryIndx!= -1&& nextBoundaryIndx!= startingBoundaryIndx) { 字符串 multipartMsg = emailText.Substring (startingBoundaryIndx + startingBoundary.Length, (nextBoundaryIndx- startingBoundaryIndx- startingBoundary.Length)); int headersIndx = multipartMsg.IndexOf (" ); 如果(headersIndx == -1) 抛出 FormatException (" ); 字符串 bodyText = multipartMsg.Substring (headersIndx).Trim(); NameValueCollection 标头= Util.ParseHeaders (multipartMsg.Trim()); messageParts.Add ( MessagePart (标题,bodyText)); } 其他 break ; startingBoundaryIndx = nextBoundaryIndx; } 其他 break ; } 如果(newLinesIndx!= -1) { 字符串 emailBodyText = emailText.Substring(newLinesIndx + 1 ); } } 其他 { int headersIndx = emailText.IndexOf(" ); 如果(headersIndx == -1) 抛出 FormatException(" 不兼容的多部分 邮件格式" ); 字符串 bodyText = emailText.Substring (headersIndx).Trim(); NameValueCollection标头= Util.ParseHeaders(emailText); messageParts.Add( MessagePart(headers,bodyText)); } 返回 messageParts; } 公共 静态 DateTime ConvertStrToUtcDateTime( string str) { 匹配m = UtcDateTimeRegex.Match(str); int 日,月,年,小时,分钟,秒; 如果(成功) { day = Convert.ToInt32(m.Groups [" ].Value); year = Convert.ToInt32(m.Groups [" ].Value); hour = Convert.ToInt32(m.Groups [" ].Value); min = Convert.ToInt32(m.Groups [" ].Value); sec = Convert.ToInt32(m.Groups [" ].Value); 开关(m.Groups [" ].Value) { 案例 " : month = 1 ; break ; 案例 " : month = 2 ; break ; 案例 " : month = 3 ; break ; 案例 " : month = 4 ; break ; 案例 " : month = 5 ; break ; 案例 " : month = 6 ; break ; 案例 " : month = 7 ; break ; 案例 " : month = 8 ; break ; 案例 " : month = 9 ; break ; 案例 " : month = 10 ; break ; 案例 " : month = 11 ; break ; 案例 " : month = 12 ; break ; 默认: 抛出 FormatException (" ); } 字符串 offsetSign = m.Groups [" span>].Value; int offsetHours = Convert.ToInt32(m.Groups [" ].Value); int offsetMinutes = Convert.ToInt32(m.Groups [" ].Value); DateTime dt = DateTime(年,月,日, 小时,分钟,秒); 如果(offsetSign == " ) { dt.AddHours(offsetHours); dt.AddMinutes(offsetMinutes); } 其他 如果(offsetSign == " -") { dt.AddHours(-offsetHours); dt.AddMinutes(-offsetMinutes); } 返回 dt; } 抛出 FormatException (" ); } } } </ messagepart > </ messagepart > </ messagepart > 偏移分钟数 </ > </ offsetsign > < ;/ > </ 分钟 </ > </ > ; </ 月份 > </ > </ 边界 > </ messagepart > </ 电子邮件 > </ > </ 电子邮件 >
", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static NameValueCollection ParseHeaders(string headerText) { NameValueCollection headers = new NameValueCollection(); StringReader reader = new StringReader(headerText); string line; string headerName = null, headerValue; int colonIndx; while ((line = reader.ReadLine()) != null) { if (line == "") break; if (Char.IsLetterOrDigit(line[0]) && (colonIndx = line.IndexOf(':')) != -1) { headerName = line.Substring(0, colonIndx); headerValue = line.Substring (colonIndx + 1).Trim(); headers.Add(headerName, headerValue); } else if (headerName != null) headers[headerName] += " " + line.Trim(); else throw new FormatException ("Could not parse headers"); } return headers; } public static List<messagepart> ParseMessageParts(string emailText) { List<messagepart> messageParts = new List<messagepart>(); int newLinesIndx = emailText.IndexOf("\r\n\r\n"); Match m = BoundaryRegex.Match(emailText); if (m.Index < emailText.IndexOf("\r\n\r\n") && m.Success) { string boundary = m.Groups["boundary"].Value; string startingBoundary = "\r\n--" + boundary; int startingBoundaryIndx = -1; while (true) { if (startingBoundaryIndx == -1) startingBoundaryIndx = emailText.IndexOf(startingBoundary); if (startingBoundaryIndx != -1) { int nextBoundaryIndx = emailText.IndexOf (startingBoundary, startingBoundaryIndx + startingBoundary.Length); if (nextBoundaryIndx != -1 && nextBoundaryIndx != startingBoundaryIndx) { string multipartMsg = emailText.Substring (startingBoundaryIndx + startingBoundary.Length, (nextBoundaryIndx - startingBoundaryIndx - startingBoundary.Length)); int headersIndx = multipartMsg.IndexOf ("\r\n\r\n"); if (headersIndx == -1) throw new FormatException ("Incompatible multipart message format"); string bodyText = multipartMsg.Substring (headersIndx).Trim(); NameValueCollection headers = Util.ParseHeaders (multipartMsg.Trim()); messageParts.Add (new MessagePart (headers, bodyText)); } else break; startingBoundaryIndx = nextBoundaryIndx; } else break; } if (newLinesIndx != -1) { string emailBodyText = emailText.Substring(newLinesIndx + 1); } } else { int headersIndx = emailText.IndexOf("\r\n\r\n"); if (headersIndx == -1) throw new FormatException("Incompatible multipart message format"); string bodyText = emailText.Substring (headersIndx).Trim(); NameValueCollection headers = Util.ParseHeaders(emailText); messageParts.Add(new MessagePart(headers, bodyText)); } return messageParts; } public static DateTime ConvertStrToUtcDateTime(string str) { Match m = UtcDateTimeRegex.Match(str); int day, month, year, hour, min, sec; if (m.Success) { day = Convert.ToInt32(m.Groups["day"].Value); year = Convert.ToInt32(m.Groups["year"].Value); hour = Convert.ToInt32(m.Groups["hour"].Value); min = Convert.ToInt32(m.Groups["minute"].Value); sec = Convert.ToInt32(m.Groups["second"].Value); switch (m.Groups["month"].Value) { case "Jan": month = 1; break; case "Feb": month = 2; break; case "Mar": month = 3; break; case "Apr": month = 4; break; case "May": month = 5; break; case "Jun": month = 6; break; case "Jul": month = 7; break; case "Aug": month = 8; break; case "Sep": month = 9; break; case "Oct": month = 10; break; case "Nov": month = 11; break; case "Dec": month = 12; break; default: throw new FormatException ("Unknown month."); } string offsetSign = m.Groups["offsetsign"].Value; int offsetHours = Convert.ToInt32(m.Groups ["offsethours"].Value); int offsetMinutes = Convert.ToInt32(m.Groups ["offsetminutes"].Value); DateTime dt = new DateTime(year, month, day, hour, min, sec); if (offsetSign == "+") { dt.AddHours(offsetHours); dt.AddMinutes(offsetMinutes); } else if (offsetSign == "-") { dt.AddHours(-offsetHours); dt.AddMinutes(-offsetMinutes); } return dt; } throw new FormatException ("Incompatible date/time string format"); } } }</messagepart></messagepart></messagepart></offsetminutes></offsethours></offsetsign></second></minute></hour></year></month></day></boundary></messagepart></email></email></email>


感谢您的重播.
但是我需要使用IMAP4协议,即通过使用Google API从代码启用imap的问题
thanks for your replay.
but i need to work with IMAP4 protocol , the problem with enabling the imap from the code by using google API


这篇关于尝试使用GoogleMailSettingsService类imapupdate启用IMAP时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆