Tạo, cập nhật và xóa danh bạ trong Gmail bằng C#

Gmail là một trong những ứng dụng email phổ biến và được sử dụng rộng rãi trên toàn cầu. Cùng với việc quản lý email, nó cho phép làm việc với lịch, danh bạ, trò chuyện, v.v. và cung cấp các dịch vụ cộng tác khác. Trong bài viết trước, bạn đã thấy cách nhập danh bạ từ tài khoản Gmail trong ứng dụng .NET. Trong bài viết này, chúng tôi sẽ giới thiệu cách tạo, cập nhật và xóa danh bạ trong tài khoản Gmail bằng C# .NET.

C# .NET API để tạo, cập nhật và xóa danh bạ Gmail

Để tạo và thao tác các liên hệ trong tài khoản Gmail, chúng tôi sẽ sử dụng Aspose.Email for .NET. Nó là một API xử lý email cho phép bạn thao tác với email và làm việc với các ứng dụng email phổ biến. Bạn có thể tải xuống DLL của API hoặc cài đặt nó từ NuGet bằng lệnh sau.

PM> Install-Package Aspose.Email

Trước khi bắt đầu làm việc, bạn cần tạo một dự án trên Bảng điều khiển dành cho nhà phát triển của Google, dự án này sẽ cho phép bạn giao tiếp với Gmail. Để tạo một tài khoản, bạn có thể làm theo hướng dẫn này.

Để truy cập và thao tác với danh bạ trong tài khoản Gmail, chúng ta cần viết một số đoạn mã để xử lý thông tin của người dùng và thực hiện xác thực. Đối với người dùng Gmail, trước tiên chúng tôi sẽ tạo một lớp có tên TestUser và sau đó kế thừa nó từ lớp GoogleUser. Sau đây là cách thực hiện đầy đủ của cả hai lớp.

using System;

namespace Aspose.Email
{
    internal enum GrantTypes
    {
        authorization_code,
        refresh_token
    }

    public class TestUser
    {
        internal TestUser(string name, string eMail, string password, string domain)
        {
            Name = name;
            EMail = eMail;
            Password = password;
            Domain = domain;
        }

        public readonly string Name;
        public readonly string EMail;
        public readonly string Password;
        public readonly string Domain;

        public static bool operator ==(TestUser x, TestUser y)
        {
            if ((object)x != null)
                return x.Equals(y);
            if ((object)y != null)
                return y.Equals(x);
            return true;
        }

        public static bool operator !=(TestUser x, TestUser y)
        {
            return !(x == y);
        }

        public static implicit operator string(TestUser user)
        {
            return user == null ? null : user.Name;
        }

        public override int GetHashCode()
        {
            return ToString().GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return obj != null && obj is TestUser && this.ToString().Equals(obj.ToString(), StringComparison.OrdinalIgnoreCase);
        }

        public override string ToString()
        {
            return string.IsNullOrEmpty(Domain) ? Name : string.Format("{0}/{1}", Domain, Name);
        }
    }
    public class GoogleUser : TestUser
    {
        public GoogleUser(string name, string eMail, string password)
            : this(name, eMail, password, null, null, null)
        { }

        public GoogleUser(string name, string eMail, string password, string clientId, string clientSecret)
            : this(name, eMail, password, clientId, clientSecret, null)
        { }

        public GoogleUser(string name, string eMail, string password, string clientId, string clientSecret, string refreshToken)
            : base(name, eMail, password, "gmail.com")
        {
            ClientId = clientId;
            ClientSecret = clientSecret;
            RefreshToken = refreshToken;
        }
        public readonly string ClientId;
        public readonly string ClientSecret;
        public readonly string RefreshToken;
    }
}

Bây giờ, chúng ta cần tạo một lớp trợ giúp sẽ đảm nhận việc xác thực tài khoản Gmail. Chúng tôi sẽ đặt tên lớp này là GoogleOAuthHelper. Sau đây là cách thực hiện hoàn chỉnh của lớp này.

using System; 
using System.Diagnostics;
using System.IO; 
using System.Net;
using System.Text;
using System.Threading; 
using System.Windows.Forms;

namespace Aspose.Email
{
    internal class GoogleOAuthHelper
    {
        public const string TOKEN_REQUEST_URL = "https://accounts.google.com/o/oauth2/token";
        public const string SCOPE = "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" + "+" + "https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2F" + "+" + "https%3A%2F%2Fmail.google.com%2F"; // IMAP & SMTP
        public const string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
        public const string REDIRECT_TYPE = "code";

        internal static string GetAccessToken(TestUser user)
        {
            return GetAccessToken((GoogleUser)user);
        }

        internal static string GetAccessToken(GoogleUser user)
        {
            string access_token;
            string token_type;
            int expires_in;
            GetAccessToken(user, out access_token, out token_type, out expires_in);
            return access_token;
        }

        internal static void GetAccessToken(GoogleUser user, out string access_token, out string token_type, out int expires_in)
        {
            access_token = null;
            token_type = null;
            expires_in = 0;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TOKEN_REQUEST_URL);
            request.CookieContainer = new CookieContainer();
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string encodedParameters = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type={3}",
            System.Web.HttpUtility.UrlEncode(user.ClientId), System.Web.HttpUtility.UrlEncode(user.ClientSecret), System.Web.HttpUtility.UrlEncode(user.RefreshToken), System.Web.HttpUtility.UrlEncode(GrantTypes.refresh_token.ToString()));
            byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
            request.ContentLength = requestData.Length;
            if (requestData.Length > 0)
                using (Stream stream = request.GetRequestStream())
                    stream.Write(requestData, 0, requestData.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string responseText = null;
            using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
                responseText = reader.ReadToEnd();
            foreach (string sPair in responseText.Replace("{", "").Replace("}", "").Replace("\"", "").Split(new string[] { ",\n" }, StringSplitOptions.None))
            {
                string[] pair = sPair.Split(':');
                string name = pair[0].Trim().ToLower();
                string value = System.Web.HttpUtility.UrlDecode(pair[1].Trim());
                switch (name)
                {
                    case "access_token":
                        access_token = value;
                        break;
                    case "token_type":
                        token_type = value;
                        break;

                    case "expires_in":
                        expires_in = Convert.ToInt32(value);
                        break;
                }
            }
            Debug.WriteLine("");
            Debug.WriteLine("---------------------------------------------------------");
            Debug.WriteLine("-----------OAuth 2.0 authorization information-----------");
            Debug.WriteLine("---------------------------------------------------------");
            Debug.WriteLine(string.Format("Login: '{0}'", user.EMail));
            Debug.WriteLine(string.Format("Access token: '{0}'", access_token));
            Debug.WriteLine(string.Format("Token type: '{0}'", token_type));
            Debug.WriteLine(string.Format("Expires in: '{0}'", expires_in));
            Debug.WriteLine("---------------------------------------------------------");
            Debug.WriteLine("");
        }

        internal static void GetAccessToken(TestUser user, out string access_token, out string refresh_token)
        {
            GetAccessToken((GoogleUser)user, out access_token, out refresh_token);
        }

        internal static void GetAccessToken(GoogleUser user, out string access_token, out string refresh_token)
        {
            string token_type;
            int expires_in;
            GoogleOAuthHelper.GetAccessToken(user, out access_token, out refresh_token, out token_type, out expires_in);
        }

        internal static void GetAccessToken(TestUser user, out string access_token, out string refresh_token, out string token_type, out int expires_in)
        {
            GetAccessToken((GoogleUser)user, out access_token, out refresh_token, out token_type, out expires_in);
        }

        internal static void GetAccessToken(GoogleUser user, out string access_token, out string refresh_token, out string token_type, out int expires_in)
        {
            string authorizationCode = GoogleOAuthHelper.GetAuthorizationCode(user, GoogleOAuthHelper.SCOPE, GoogleOAuthHelper.REDIRECT_URI, GoogleOAuthHelper.REDIRECT_TYPE);
            GoogleOAuthHelper.GetAccessToken(authorizationCode, user, out access_token, out token_type, out expires_in, out refresh_token);
        }

        internal static void GetAccessToken(string authorizationCode, TestUser user, out string access_token, out string token_type, out int expires_in, out string refresh_token)
        {
            GetAccessToken(authorizationCode, (GoogleUser)user, out access_token, out token_type, out expires_in, out refresh_token);
        }

        internal static void GetAccessToken(string authorizationCode, GoogleUser user, out string access_token, out string token_type, out int expires_in, out string refresh_token)
        {
            access_token = null;
            token_type = null;
            expires_in = 0;
            refresh_token = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TOKEN_REQUEST_URL);
            request.CookieContainer = new CookieContainer();
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string encodedParameters = string.Format("client_id={0}&code={1}&client_secret={2}&redirect_uri={3}&grant_type={4}", System.Web.HttpUtility.UrlEncode(user.ClientId), System.Web.HttpUtility.UrlEncode(authorizationCode), System.Web.HttpUtility.UrlEncode(user.ClientSecret), System.Web.HttpUtility.UrlEncode(REDIRECT_URI), System.Web.HttpUtility.UrlEncode(GrantTypes.authorization_code.ToString()));
            byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
            request.ContentLength = requestData.Length;
            if (requestData.Length > 0)
                using (Stream stream = request.GetRequestStream())
                    stream.Write(requestData, 0, requestData.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string responseText = null;
            using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
                responseText = reader.ReadToEnd();
            foreach (string sPair in responseText.Replace("{", "").Replace("}", "").Replace("\"", "").Split(new string[] { ",\n" }, StringSplitOptions.None))
            {
                string[] pair = sPair.Split(':');
                string name = pair[0].Trim().ToLower();
                string value = System.Web.HttpUtility.UrlDecode(pair[1].Trim());
                switch (name)
                {
                    case "access_token":
                        access_token = value;
                        break;
                    case "token_type":
                        token_type = value;
                        break;

                    case "expires_in":
                        expires_in = Convert.ToInt32(value);
                        break;

                    case "refresh_token":
                        refresh_token = value;
                        break;
                }
            }

            Debug.WriteLine(string.Format("Authorization code: '{0}'", authorizationCode));
            Debug.WriteLine(string.Format("Access token: '{0}'", access_token));
            Debug.WriteLine(string.Format("Refresh token: '{0}'", refresh_token));
            Debug.WriteLine(string.Format("Token type: '{0}'", token_type));
            Debug.WriteLine(string.Format("Expires in: '{0}'", expires_in));
            Debug.WriteLine("---------------------------------------------------------");
            Debug.WriteLine("");
        }

        internal static string GetAuthorizationCode(TestUser acc, string scope, string redirectUri, string responseType)
        {
            return GetAuthorizationCode((GoogleUser)acc, scope, redirectUri, responseType);
        }

        internal static string GetAuthorizationCode(GoogleUser acc, string scope, string redirectUri, string responseType)
        {
            Debug.WriteLine("");
            Debug.WriteLine("---------------------------------------------------------");
            Debug.WriteLine("-----------OAuth 2.0 authorization information-----------");
            Debug.WriteLine("---------------------------------------------------------");
            Debug.WriteLine(string.Format("Login: '{0}'", acc.EMail));
            string authorizationCode = null;
            string error = null;
            string approveUrl = string.Format("https://accounts.google.com/o/oauth2/auth?redirect_uri={0}&response_type={1}&client_id={2}&scope={3}", redirectUri, responseType, acc.ClientId, scope);

            AutoResetEvent are0 = new AutoResetEvent(false);
            Thread t = new Thread(delegate()
            {
                bool doEvents = true;
                WebBrowser browser = new WebBrowser();
                browser.AllowNavigation = true;
                browser.DocumentCompleted += delegate (object sender, WebBrowserDocumentCompletedEventArgs e) { doEvents = false; };
                Form f = new Form();
                f.FormBorderStyle = FormBorderStyle.FixedToolWindow;
                f.ShowInTaskbar = false;
                f.StartPosition = FormStartPosition.Manual;
                f.Location = new System.Drawing.Point(-2000, -2000);
                f.Size = new System.Drawing.Size(1, 1);
                f.Controls.Add(browser);
                f.Load += delegate (object sender, EventArgs e)
                {
                    try
                    {
                        browser.Navigate("https://accounts.google.com/Logout");
                        doEvents = true;
                        while (doEvents) Application.DoEvents();
                        browser.Navigate("https://accounts.google.com/ServiceLogin?sacu=1");
                        doEvents = true;
                        while (doEvents) Application.DoEvents();
                        HtmlElement loginForm = browser.Document.Forms["gaia_loginform"];
                        if (loginForm != null)
                        {
                            HtmlElement userName = browser.Document.All["Email"];

                            userName.SetAttribute("value", acc.EMail);
                            loginForm.InvokeMember("submit");
                            doEvents = true;
                            while (doEvents)
                                Application.DoEvents();

                            loginForm = browser.Document.Forms["gaia_loginform"];
                            HtmlElement passwd = browser.Document.All["Passwd"];
                            passwd.SetAttribute("value", acc.Password);

                            loginForm.InvokeMember("submit");
                            doEvents = true;
                            while (doEvents)
                                Application.DoEvents();
                        }
                        else
                        {
                            error = "Login form is not found in \n" + browser.Document.Body.InnerHtml;
                            return;
                        }
                        browser.Navigate(approveUrl);
                        doEvents = true;
                        while (doEvents) Application.DoEvents();
                        HtmlElement approveForm = browser.Document.Forms["connect-approve"];
                        if (approveForm != null)
                        {
                            HtmlElement submitAccess = browser.Document.All["submit_access"];
                            submitAccess.SetAttribute("value", "true");
                            approveForm.InvokeMember("submit");
                            doEvents = true;
                            while (doEvents)
                                Application.DoEvents();
                        }
                        else
                        {
                            error = "Approve form is not found in \n" + browser.Document.Body.InnerHtml;
                            return;
                        }
                        HtmlElement code = browser.Document.All["code"];
                        if (code != null)
                            authorizationCode = code.GetAttribute("value");
                        else
                            error = "Authorization code is not found in \n" + browser.Document.Body.InnerHtml;
                    }
                    catch (Exception ex)
                    {
                        error = ex.Message;
                    }
                    finally
                    {
                        f.Close();
                    }
                };
                Application.Run(f);
                are0.Set();
            });
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            are0.WaitOne();
            if (error != null)
                throw new Exception(error);
            return authorizationCode;
        }
    }
}

Tạo Liên hệ trên Gmail trong C#

Sau đây là các bước tạo liên hệ trên Gmail bằng C#.

  • Đầu tiên, tạo người dùng Google, nhận mã thông báo truy cập và khởi tạo đối tượng IGmailClient.
  • Sau đó, tạo một đối tượng của lớp Liên hệ.
  • Đặt các thuộc tính của liên hệ như tên, tiền tố, nghề nghiệp, v.v.
  • Để đặt địa chỉ bưu điện, hãy tạo một phiên bản của PostalAddress và đặt các thuộc tính của nó.
  • Thêm địa chỉ mới tạo vào bộ sưu tập bằng phương pháp Contact.PhysicalAddresses.Add (PostalAddress).
  • Đặt chi tiết số điện thoại bằng lớp PhoneNumber.
  • Thêm chi tiết số điện thoại vào bộ sưu tập bằng phương pháp Contact.PhoneNumbers.Add (PhoneNumber).
  • Tạo một phiên bản của lớp EmailAddress, đặt địa chỉ email và gán cho địa chỉ liên hệ.
  • Cuối cùng, gọi phương thức IGmailClient.CreateContact (Liên hệ) để tạo liên hệ Gmail.

Mẫu mã sau đây cho biết cách tạo liên hệ trên Gmail bằng C#.

// Khởi tạo người dùng Google
GoogleUser User = new GoogleUser("user", "email address", "password", "clientId", "client secret");
string accessToken;
string refreshToken;

// Nhận mã thông báo truy cập
GoogleOAuthHelper.GetAccessToken(User, out accessToken, out refreshToken);

// Nhận ứng dụng khách Gmail
IGmailClient client = GmailClient.GetInstance(accessToken, User.EMail);

// Tạo một liên hệ
Contact contact = new Contact();
contact.Prefix = "Prefix";
contact.GivenName = "GivenName";
contact.Surname = "Surname";
contact.MiddleName = "MiddleName";
contact.DisplayName = "Test User 1";
contact.Suffix = "Suffix";
contact.JobTitle = "JobTitle";
contact.DepartmentName = "DepartmentName";
contact.CompanyName = "CompanyName";
contact.Profession = "Profession";
contact.Notes = "Notes";

// Đặt địa chỉ bưu điện
PostalAddress address = new PostalAddress();
address.Category = PostalAddressCategory.Work;
address.Address = "Address";
address.Street = "Street";
address.PostOfficeBox = "PostOfficeBox";
address.City = "City";
address.StateOrProvince = "StateOrProvince";
address.PostalCode = "PostalCode";
address.Country = "Country";
contact.PhysicalAddresses.Add(address);

// Đặt số điện thoại
PhoneNumber pnWork = new PhoneNumber();
pnWork.Number = "323423423423";
pnWork.Category = PhoneNumberCategory.Work;
contact.PhoneNumbers.Add(pnWork);
PhoneNumber pnHome = new PhoneNumber();
pnHome.Number = "323423423423";
pnHome.Category = PhoneNumberCategory.Home;
contact.PhoneNumbers.Add(pnHome);
PhoneNumber pnMobile = new PhoneNumber();
pnMobile.Number = "323423423423";
pnMobile.Category = PhoneNumberCategory.Mobile;
contact.PhoneNumbers.Add(pnMobile);

// Đặt các thuộc tính khác
contact.Urls.Blog = "Blog.ru";
contact.Urls.BusinessHomePage = "BusinessHomePage.ru";
contact.Urls.HomePage = "HomePage.ru";
contact.Urls.Profile = "Profile.ru";
contact.Events.Birthday = DateTime.Now.AddYears(-30);
contact.Events.Anniversary = DateTime.Now.AddYears(-10);
contact.InstantMessengers.AIM = "AIM";
contact.InstantMessengers.GoogleTalk = "GoogleTalk";
contact.InstantMessengers.ICQ = "ICQ";
contact.InstantMessengers.Jabber = "Jabber";
contact.InstantMessengers.MSN = "MSN";
contact.InstantMessengers.QQ = "QQ";
contact.InstantMessengers.Skype = "Skype";
contact.InstantMessengers.Yahoo = "Yahoo";
contact.AssociatedPersons.Spouse = "Spouse";
contact.AssociatedPersons.Sister = "Sister";
contact.AssociatedPersons.Relative = "Relative";
contact.AssociatedPersons.ReferredBy = "ReferredBy";
contact.AssociatedPersons.Partner = "Partner";
contact.AssociatedPersons.Parent = "Parent";
contact.AssociatedPersons.Mother = "Mother";
contact.AssociatedPersons.Manager = "Manager";

// Đặt địa chỉ email
EmailAddress eAddress = new EmailAddress();
eAddress.Address = "email@gmail.com";
contact.EmailAddresses.Add(eAddress);

// Tạo liên hệ trên Gmail
string contactUri = client.CreateContact(contact);

Cập nhật Địa chỉ liên hệ trên Gmail trong C#

Bạn cũng có thể cập nhật thông tin chi tiết của một địa chỉ liên hệ Gmail sau khi truy cập nó. Sau đây là các bước để cập nhật địa chỉ liên hệ trong tài khoản Gmail bằng C#.

Mẫu mã sau đây cho biết cách cập nhật địa chỉ liên hệ trong Gmail bằng C#.

// Khởi tạo người dùng Google
GoogleUser User = new GoogleUser("user", "email address", "password", "clientId", "client secret");
string accessToken;
string refreshToken;

// Nhận mã thông báo truy cập
GoogleOAuthHelper.GetAccessToken(User, out accessToken, out refreshToken);

// Nhận IGmailClient
using (IGmailClient client = GmailClient.GetInstance(accessToken, User.EMail))
{
    // Nhận tất cả các địa chỉ liên hệ
    Contact[] contacts = client.GetAllContacts();
    Contact contact = contacts[0];
    contact.JobTitle = "Manager IT";
    contact.DepartmentName = "Customer Support";
    contact.CompanyName = "Aspose";
    contact.Profession = "Software Developer";
    
    // Cập nhật liên hệ
    client.UpdateContact(contact);
}

Xóa địa chỉ liên hệ trên Gmail trong C#

Cuối cùng, hãy xem cách xóa liên hệ Gmail bằng C#. Sau đây là các bước để thực hiện thao tác này.

Mẫu mã sau đây cho biết cách xóa địa chỉ liên hệ trên Gmail trong C#.

// Khởi tạo người dùng Google
GoogleUser User = new GoogleUser("user", "email address", "password", "clientId", "client secret");
string accessToken;
string refreshToken;

// Nhận mã thông báo truy cập
GoogleOAuthHelper.GetAccessToken(User, out accessToken, out refreshToken);

// Nhận IGmailClient
using (IGmailClient client = GmailClient.GetInstance(accessToken, User.EMail))
{
    // Nhận tất cả các địa chỉ liên hệ
    Contact[] contacts = client.GetAllContacts();
    Contact contact = contacts[0];
    
    // Xóa liên lạc
    client.DeleteContact(contact.Id.GoogleId);

}

Nhận giấy phép API miễn phí

Bạn có thể sử dụng Aspose.Email for .NET mà không có giới hạn đánh giá bằng cách sử dụng giấy phép tạm thời miễn phí.

Sự kết luận

Trong bài viết này, bạn đã học cách tạo và cập nhật danh bạ trong tài khoản Gmail trong C# .NET. Hơn nữa, bạn đã biết cách xóa địa chỉ liên hệ Gmail theo chương trình. Bên cạnh đó, bạn có thể truy cập tài liệu để khám phá các tính năng khác của Aspose.Email dành cho .NET. Trong trường hợp bạn có bất kỳ câu hỏi nào, bạn có thể đăng lên diễn đàn của chúng tôi.

Xem thêm