Bài viết hôm nay, 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 ta cần tạo một ứng dụng và đăng ký sử dụng quyền đọc email từ google.
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, 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 nhấn nút Allow, ứng dụng 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ó 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#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
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; } } } } |
Chúc thành công!
Nguồn: laptrinhvb.net