I'm making a small Windows Application for my project. I followed the document of Google and some people in this forum to write a method to read all Gmail messages in "INBOX" of my Gmail. I could get Gmail messages in its body part but I just could get 5 emails instead of all of my email messages. I tried to use the property "MaxResult" to set maximum emails that I wanted to get but nothing happened.
This is my method:
private async Task GetMAILs()
{
try
{
UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for read-only access to the authenticated
// user's account, but not other types of account access.
new[] { GmailService.Scope.GmailReadonly, GmailService.Scope.MailGoogleCom, GmailService.Scope.GmailModify },
"an thanh",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var gmailService = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
//var request = new UsersResource.MessagesResource.ListRequest(gmailService, "me");
var emailListRequest = gmailService.Users.Messages.List("[email protected]");
emailListRequest.LabelIds = "INBOX";
//emailListRequest.IncludeSpamTrash = false;
emailListRequest.Q = "in:unread in:inbox";
emailListRequest.MaxResults = 100;
//get our emails
var emailListResponse = await emailListRequest.ExecuteAsync();
if (emailListResponse != null && emailListResponse.Messages != null)
{
//loop through each email and get what fields you want...
foreach (var email in emailListResponse.Messages)
{
//FORM.MessageBox.Show(email.Id);
//var request = new UsersResource.MessagesResource.ListRequest(gmailService, "me");
//IList<Message> messages = request.Execute().Messages;
string from = "";
string date = "";
string subject = "";
string decoded = "";
var emailInfoRequest = gmailService.Users.Messages.Get("[email protected]",email.Id);
//make another request for that email id...
var emailInfoResponse = await emailInfoRequest.ExecuteAsync();
if (emailInfoResponse != null)
{
//loop through the headers and get the fields we need...
foreach (var mParts in emailInfoResponse.Payload.Headers)
{
if (mParts.Name == "Date")
{
date = mParts.Value;
}
else if (mParts.Name == "From")
{
from = mParts.Value;
}
else if (mParts.Name == "Subject")
{
subject = mParts.Value;
}
}
foreach (var ms_part in emailInfoResponse.Payload.Parts)
{
if (ms_part.MimeType == "text/plain")
{
byte[] data = FromBase64ForUrlString(ms_part.Body.Data);
decoded = Encoding.UTF8.GetString(data);
}
}
}
bd.AppendLine(string.Format("Từ: {0}", from));
bd.AppendLine(subject);
bd.AppendLine(date);
bd.AppendLine("Content: ");
bd.AppendLine(decoded);
bd.AppendLine("-------End-------");
bd.AppendLine("----------------------------------------------------");
//now you have the data you want....
richTextBox1.Text = bd.ToString();
}
}
}
catch (Exception ex)
{
FORM.MessageBox.Show("Failed to get messages!: " + ex.Message, "Failed Messages!", FORM.MessageBoxButtons.OK);
}
}
Method to convert Binary data to String:
public byte[] FromBase64ForUrlString(string base64ForUrlInput)
{
int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
result.Append(String.Empty.PadRight(padChars, '='));
result.Replace('-', '+');
result.Replace('_', '/');
return Convert.FromBase64String(result.ToString());
}
Method to call Task "GetMAILs()":
private void btGet_Click(object sender, EventArgs e)
{
Test2();
}
private async void Test2()
{
await GetMAILs();
}
Sorry I'm just a freshman with Gmail API. I'll be grateful for anyhelp from everyone.