NEWS

[C#] Hướng dẫn đọc gmail sử dụng Gmail API lập trình Csharp

[C#] Hướng dẫn đọc gmail sử dụng Gmail API lập trình Csharp
Đăng bởi: Thảo Meo - Lượt xem: 14821 13:48:56, 29/05/2018C#   In bài viết

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.

Xin cấp quyền đọc email

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:

save permission read gmail csharp

 

Và dưới đây, là giao diện đọc email của ứng dụng:

 

Read Gmail C#

 

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!

DOWNLOAD SOURCE

Tags:

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn đọc gmail sử dụng Gmail API lập trình Csharp
Đăng bởi: Thảo Meo - Lượt xem: 14821 13:48:56, 29/05/2018C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.