- [C#] Hướng dẫn fix lỗi Visual Studio 2022 not Support Target Net Framework 4.5.2
- [C#] Giới thiệu thư viện Sunny UI thiết kế giao diện trên Winform
- [DATABASE] Hướng dẫn thêm và cập nhật Extended Property Column trong Table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng Vertical Gridview để hiển thị thông tin sản phẩm
- [C#] Hướng dẫn sử dụng Json Schema để Validate chuỗi string có phải json
- [C#] Hướng dẫn sử dụng công cụ Clean Code trên Visual Studio
- [C#] Hướng dẫn Drag and Drop File vào RichTextBox
- [C#] Hướng dẫn tạo hiệu ứng Karaoke Text Effect Winform
- [C#] Sử dụng thư viện ZedGraph vẽ biểu đồ Line, Bar, Pie trên Winform
- [DATABASE] Hướng dẫn sort sắp xếp địa chỉ IP trên sqlserver sử dụng hàm PARSENAME
- [C#] Theo dõi sử kiện process Start hay Stop trên Winform
- [ASP.NET] Chia sẻ source code chụp hình sử dụng camera trên website
- [C#] Chạy ứng dụng trên Virtual Desktop (màn hình ảo) Winform
- [C#] Mã hóa và giải mã Data Protection API trên winform
- [C#] Hướng dẫn tạo Gradient Background trên Winform
- [DATABASE] Hướng dẫn convert Epoch to DateTime trong sqlserver
- [DATABASE] Hướng dẫn sử dụng STRING_AGG và CONCAT_WS trong sqlserver 2017
- [C#] Hướng dẫn Copy With All Property in Class Object
- [DEVEXPRESS] Hướng dẫn load Json DataSource vào GridView
- [C#] Hướng dẫn tạo chữ ký trên winform Signature Pad
[C#] Hướng dẫn đọc gmail sử dụng Gmail API lập trình Csharp
Chào các bạn đọc thân mến, bài viết hôm nay, mình sẽ tiếp tục hướng dẫn các bạn cách đọc Email từ Gmail (Google Mail) sử dụng Gmail Api V1 C#.
- Đầ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
Source code ứng dụng C#:
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!