C# .NET - Gmail account login through asp.net page

Asked By Shailendrasinh Parmar on 05-Jul-11 04:12 AM
Hi Friends,

I have created a login page for my site. Now I need to pass my gmail credentials to those textboxes and on clicking Login button, I need to redirect to gmail Inbox direcly in another tab/ another browser window.

How can I do this?

Thanks in advance.
Ravi S replied to Shailendrasinh Parmar on 05-Jul-11 04:15 AM
HI

refer this

<form  method="post" action="https://www.google.com/accounts/ServiceLoginAuth?service=mail" id="gaia_loginform">
 
<input type="hidden" value="http://mail.google.com/mail/?hl=en&tab=wm" id="continue" name="continue"/>
 
<input type="hidden" value="mail" id="service" name="service"/>

  Username:
<input type="text"  value="" size="18" id="Email" name="Email"/>
 
  Password:
<input type="password"  size="18" id="Passwd" name="Passwd"/>
 
<input type="submit" value="Sign in" name="signIn"/>  

</form>
Ravi S replied to Shailendrasinh Parmar on 05-Jul-11 04:15 AM
HI


Try this...

http://www.codeproject.com/KB/gadgets/GadgetInterop.aspx

I hope it will help you.

Jitendra Faye replied to Shailendrasinh Parmar on 05-Jul-11 04:16 AM

Follow these steps-


1. Download the DotNetOpenAuth Libraries. Choose the most appropriate version for development platform.
2. Extract the downloaded compressed file on your hard drive.
3. On your project, Add Reference to "DotNetOpenAuth.dll"
4. On your login page's HTML Code, paste the following.
view plainprint?

    <form id="form1" runat="server"> 
      <div id="loginform"> 
        <div id="NotLoggedIn" runat="server"> 
          Log in with <img src="http://www.google.com/favicon.ico" /> 
            <asp:Button ID="btnLoginToGoogle" Runat="server" Text="Google" OnCommand="OpenLogin_Click" 
              CommandArgument="https://www.google.com/accounts/o8/id" /> 
          <p /><asp:Label runat="server" ID="lblAlertMsg" /> 
        </div> 
      </div> 
    </form> 


Take note of the URL: https://www.google.com/accounts/o8/id - this is the unique OpenID URL of Google Account.

5. Include the following namespaces on your "Using" directive.

view plainprint?

    using DotNetOpenAuth.OpenId; 
    using DotNetOpenAuth.OpenId.RelyingParty; 


6. On the Page_Load & OpenLogin_Click, use the following codes.

view plainprint?

    protected void Page_Load(object sender, EventArgs e) 
    {    
      OpenIdRelyingParty rp = new OpenIdRelyingParty(); 
      var r = rp.GetResponse(); 
      if (r != null) 
      { 
        switch (r.Status) 
        { 
          case AuthenticationStatus.Authenticated: 
            NotLoggedIn.Visible = false; 
            Session["GoogleIdentifier"] = r.ClaimedIdentifier.ToString(); 
            Response.Redirect("Main.aspx"); //redirect to main page of your website 
            break; 
          case AuthenticationStatus.Canceled: 
            lblAlertMsg.Text = "Cancelled."; 
            break; 
          case AuthenticationStatus.Failed: 
            lblAlertMsg.Text = "Login Failed."; 
            break; 
        } 
      } 
   
    protected void OpenLogin_Click(object src, CommandEventArgs e) 
    { 
      string discoveryUri = e.CommandArgument.ToString(); 
      OpenIdRelyingParty openid = new OpenIdRelyingParty(); 
      var b = new UriBuilder(Request.Url) { Query = "" }; 
      var req = openid.CreateRequest(discoveryUri, b.Uri, b.Uri); 
      req.RedirectToProvider(); 
    } 


7. Run the project. It should look like the following screens.


a. Login page

b. Main Page (showing the returned identifier by Google)
http://lh6.ggpht.com/_uU5cLRayUdQ/TKFOPuPCp8I/AAAAAAAAEos/T2wPIAe0Fi0/s800/OpenId%20Code%202.PNG


Follow this link also-

http://www.fryan0911.com/2010/09/use-google-openid-authentication-in.html

TSN ... replied to Shailendrasinh Parmar on 05-Jul-11 04:19 AM
hi..

Look at this article hope it may be use ful for you...

http://www.codeproject.com/KB/gadgets/GadgetInterop.aspx

Riley K replied to Shailendrasinh Parmar on 05-Jul-11 04:19 AM
You cannot do this directly, you have to use some API from Google,

You can use Google Authenticaltion ,
check this link

http://code.google.com/apis/accounts/docs/AuthForWebApps.html

Kirtan Patel replied to Shailendrasinh Parmar on 05-Jul-11 04:19 AM
Hi you can not do authentication like this directly but if you want to read gmail inbox in your page you can communicate gmail server with POP3 / IMAP libraries 

here is code from http://www.codeproject.com/KB/applications/ReadGmailInboxMessage.aspx for POP3 Client of gmail .code is so looooong but its good enough to load gmail inbox to your page
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;
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);
	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");
	}
}
}
Shailendrasinh Parmar replied to Ravi S on 05-Jul-11 05:03 AM
I tried this, but it redirects me to google login page with my credentials written in Textboxes for username and password.
SRE replied to Shailendrasinh Parmar on 05-Jul-11 05:11 AM
Hi Refer These Links

http://prasadmaduranga.blogspot.com/2010/01/saml-single-sign-on-for-google-apps-in.html

http://www.codeproject.com/KB/gadgets/GadgetInterop.aspx
Ravi S replied to Shailendrasinh Parmar on 05-Jul-11 05:17 AM
It is working for me.

Give your gmail credentials.

So that it redirects to gmail login pageand you have to give your password.

Try this...
Shailendrasinh Parmar replied to Ravi S on 05-Jul-11 05:30 AM
No, I don't want to be redirected to login page again.

I want: 

- I will type username and password on my site. and will click "Login to Gmail" button.
- on clicking that button, my credentials will be validated and I will directly redirected to Gmail Inbox page.
- The gmail login page will not appear at all.

Please help.
Rakesh Chandrasekaran replied to Jitendra Faye on 02-May-12 04:33 AM
hi,
can you plz lemme know how to send email without entering gmailpage.
i mean with the same method i need to send email.
user logs in with this method to my page, he selects receivers emails id and when click on send the email has to be deliver from my end.
can you help me in this..?
awaiting your reply..
satham hussain replied to Ravi S on 07-May-13 07:33 AM
end of post