GMAIL
phải không?Hôm nay ngồi tìm hiểu về cách thứ hoạt động của và mình thấy nó có một đường link hướng dẫn việc lấy thông tin mail trên
GMAIL
từ API cũng khá hay nên mình viết bài chia sẽ cho mọi người cùng biết luôn. Và cùng nhờ bên LapTrinhVB.Net để lấy dữ liệu được từ nó.Chúng ta bắt đầu nhé.
- Đầu tiên, để sử dụng được Api của google các bạn cần tạo một ứng dụng và đăng ký sử dụng quyền đọc email từ google.Các bạn vào link bên dưới để tạo một ứng dụng.
https://developers.google.com/gmail/api/quickstart/dotnet
Sau khi đăng ký ứng dụng xong các bạn tải
file client_secret.json
vào thư mục ứng dụng để thực hiện.Hiện nay, google đang sử dụng
Permission Realtime
, nghĩa là khi ứng dụng của bạn sử dụng dịch vụ của google muốn đọc mail từ cần phải cấp quyền trực tiếp.Dưới đây là giao diện yêu cầu cấp quyền của Gmail API.
Sau khi bạn nhấn nút Allow, ứng dụng của bạn sẽ tạo ra một
file Google.Apis.Auth.OAuth2.Responses.TokenResponse-user
, để ghi nhớ đăng nhập của mỗi email.Thư mục chứa file lưu
permission
ở hình bên dưới:Và dưới đây, là giao diện đọc email của ứng dụng:
Các bạn có thể tham khảo link hướng dẫn sử dụng Google API C# ở link bên dưới:
https://developers.google.com/gmail/api/quickstart/dotnet?hl=vi
Full Source Code Csharp:
using Google.Apis.Auth.OAuth2; using Google.Apis.Gmail.v1; using Google.Apis.Gmail.v1.Data; using Google.Apis.Services; using Google.Apis.Util.Store; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ReadEmail { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string[] Scopes = { GmailService.Scope.GmailReadonly }; GmailService service; string myEmail = "nguyeenthao88@gmail.com"; string ApplicationName = "Gmail API .NET Quickstart"; private void button1_Click(object sender, EventArgs e) { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Gmail API service. service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); var inboxlistRequest = service.Users.Messages.List(myEmail); inboxlistRequest.LabelIds = "INBOX"; inboxlistRequest.IncludeSpamTrash = false; //get our emails var emailListResponse = inboxlistRequest.Execute(); if (emailListResponse != null && emailListResponse.Messages != null) { //loop through each email and get what fields you want... foreach (var email in emailListResponse.Messages) { var emailInfoRequest = service.Users.Messages.Get(myEmail, email.Id); var emailInfoResponse = emailInfoRequest.Execute(); if (emailInfoResponse != null) { String from = ""; String date = ""; String subject = ""; //loop through the headers to get from,date,subject, body 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; } } table.Rows.Add(email.Id, from, subject, date); } } dataGridView1.DataSource = table; } } public static 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()); } DataTable table; private void Form1_Load(object sender, EventArgs e) { table = new DataTable(); table.Columns.Add("Email ID", typeof(string)); table.Columns.Add("From", typeof(string)); table.Columns.Add("Subject", typeof(string)); table.Columns.Add("Date", typeof(string)); } public string GetContentByEmailID(string EmailID) { var emailInfoRequest = service.Users.Messages.Get(myEmail, EmailID); var emailInfoResponse = emailInfoRequest.Execute(); if (emailInfoResponse != null) { String from = ""; String date = ""; String subject = ""; //loop through the headers to get from,date,subject, body 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; } if (date != "" && from != "") { foreach (MessagePart p in emailInfoResponse.Payload.Parts) { if (p.MimeType == "text/html") { byte[] data = FromBase64ForUrlString(p.Body.Data); string decodedString = Encoding.UTF8.GetString(data); return decodedString; } } } } } return ""; } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (dataGridView1.SelectedCells.Count > 0) { int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex; DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex]; string email_id = Convert.ToString(selectedRow.Cells["Email ID"].Value); string bodyEmail = GetContentByEmailID(email_id); webBrowser1.DocumentText = bodyEmail; } } } }
Các bạn có thể download source của mình bên dưới để tham kháo.
Chúc các bạn thành công!
DOWNLOAD GMAIL API
PASSWORD UNZIP:
HUNG.PRO.VN
Theo LapTrinhVB.Net
Comments