示例#1
0
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_id.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = Environment.GetEnvironmentVariable("LocalAppData");
                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;
                Console.WriteLine("Credential file saved to: " + credPath);
            }


            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });


            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");


            var response = request.Execute();

            Console.WriteLine("Jobs Applied To:");
            if (response != null && response.Messages.Count > 0)
            {
                foreach (var messages in response.Messages)
                {
                    var email = service.Users.Messages.Get("me", messages.Id).Execute();
                    if (JobsAppliedToKeyWords.Any(x => email.Snippet.Contains(x)))
                    {
                        Console.WriteLine(email.Snippet + "\n");
                    }
                }
            }
            else
            {
                Console.WriteLine("No messages found.");
            }
            Console.Read();
        }
示例#2
0
        /// <summary>
        /// List all Messages of the user's mailbox matching the query.
        /// </summary>
        /// <param name="service">Gmail API service instance.</param>
        /// <param name="userId">User's email address. The special value "me"
        /// can be used to indicate the authenticated user.</param>
        /// <param name="query">String used to filter Messages returned.</param>
        public List <Google.Apis.Gmail.v1.Data.Message> ListMessages(string box)
        {
            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                //Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });


            List <Google.Apis.Gmail.v1.Data.Message> result = new List <Google.Apis.Gmail.v1.Data.Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
            request.LabelIds = box;
            //request.Q = query;
            long max = 200;

            request.MaxResults = max;

            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Debug.WriteLine(" 4 An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
        public static List<Message> GetMessagesList(GmailService service, string userId)
        {
            List<Message> result = new List<Message>();
            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);

            do
            {
                 ListMessagesResponse response = request.Execute();
                 result.AddRange(response.Messages);
                 request.PageToken = response.NextPageToken;
            } while (!string.IsNullOrEmpty(request.PageToken));

            return result;
        }
        public IEnumerable <Message> GetRecentMessages()
        {
            int             currentIndex = 1;
            IList <Message> messages     = null;

            try
            {
                UsersResource.MessagesResource.ListRequest request = _gmailService.Users.Messages.List("me");

                request.MaxResults = _settings.BatchSize;

                request.Q = $"from:{_settings.From} newer_than:{_settings.MaxNumerOfDaysToFetchEmail}d";

                messages = request.Execute().Messages;

                if (messages == null)
                {
                    _logger.Warning("No messages returned from server");
                    yield break;
                }
                else
                {
                    _logger.Information("{messagesCount} messages fetched from Google " +
                                        "for the last {maxDays} days",
                                        messages.Count, _settings.MaxNumerOfDaysToFetchEmail);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "{errorMessage}", ex.Message);
                yield break;
            }

            using (Database db = new Database())
                foreach (var message in messages)
                {
                    _logger.Verbose("Processing {currentIndex}/{messageCount}", currentIndex++, messages.Count);

                    var email = db.ForwardedEmails.Find(message.Id);
                    if (email == null)
                    {
                        yield return(GetMessage(message.Id));
                    }
                    else
                    {
                        _logger.Warning("{messageId} was already attempted/processed", message.Id);
                        _logger.Debug("{subject}", email.Subject);
                    }
                }
        }
示例#5
0
        /// <summary>
        /// List all Messages of the user's mailbox matching the query.
        /// </summary>
        /// <param name="service">Gmail API service instance.</param>
        /// <param name="userId">User's email address. The special value "me"
        /// can be used to indicate the authenticated user.</param>
        /// <param name="query">String used to filter Messages returned.</param>
        static List <Message> ListMessages(GmailService service, String userId, String query)
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            request.Q = query;


            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();

                    string   listfile = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location) + ".list";
                    string[] SavedId  = { "0" };

                    if (File.Exists(listfile))
                    {
                        SavedId = File.ReadAllLines(listfile);
                    }

                    // исключаем сообщения, выгруженные ранее
                    var messages = response.Messages.Where(m => !SavedId.Contains(m.Id));

                    if (messages != null && messages.ToList().Count > 0)
                    {
                        result.AddRange(messages);
                    }

                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    string error = e.Message;
                    if (e.InnerException != null)
                    {
                        error = e.InnerException.Message;
                    }

                    string logfile = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location) + ".log";
                    WriteErrorToLog(logfile, e.ToString());

                    Console.WriteLine(e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#6
0
        public GetInformationsViewModel GetInformations()
        {
            string         path = HttpContext.Current.Server.MapPath("~/App_Data/client_secret.json");
            UserCredential credential;

            using (var stream =
                       new FileStream(path, 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.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
            // List labels.
            IList <Label> labels = request.Execute().Labels;

            UsersResource.MessagesResource.ListRequest requestMessages = service.Users.Messages.List("me");
            IList <Message> messages     = requestMessages.Execute().Messages;
            List <Message>  messagesFull = new List <Message>();

            foreach (var message in messages)
            {
                var messageFull = service.Users.Messages.Get("me", message.Id).Execute();
                messagesFull.Add(messageFull);
            }


            var getInformationsViewModel = new GetInformationsViewModel();

            getInformationsViewModel.Labels   = labels;
            getInformationsViewModel.Messages = messagesFull;
            return(getInformationsViewModel);
        }
示例#7
0
        /*Retrieves a list of messages given the userId, query, and max results to be returned */
        public static List <MessageG> ListMessages(GmailService service, String userId, String query, int maxResults)
        {
            List <MessageG> result = new List <MessageG>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            request.MaxResults = maxResults;
            //request.Q = query; //sets Query

            try {
                ListMessagesResponse response = request.Execute();
                result.AddRange(response.Messages);
            } catch (Exception e) {
                Debug.WriteLine("An error occured: " + e.Message);
            }
            return(result);
        }
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");

            // List labels.
            IList <Message> messages = request.Execute().Messages;

            Console.WriteLine("Messages:");
            if (messages != null && messages.Count > 0)
            {
                foreach (var labelItem in messages)
                {
                    var texta = service.Users.Messages.Get("me", labelItem.Id).Execute();
                    Console.WriteLine("{0}", texta.Snippet);
                }
            }
            else
            {
                Console.WriteLine("No labels found.");
            }
            Console.Read();
        }
示例#9
0
        public static List <Message> ListMessages(GmailService service, string userId, string query)
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            request.Q = query;
            do
            {
                try {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                } catch (Exception e) {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            }while (!string.IsNullOrEmpty(request.PageToken));
            return(result);
        }
示例#10
0
        public Stack <string> GetMessages(string query, ref string lastId)
        {
            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(email);
            if (!String.IsNullOrEmpty(query))
            {
                request.Q = query; // "label:отчеты-aliter-axi";
            }
            request.MaxResults = Int32.MaxValue;

            Stack <string> buffer = new Stack <string>();
            string         first  = String.Empty;

            do
            {
                ListMessagesResponse response = request.Execute();
                IList <Message>      messages = response.Messages;
                if (messages == null)
                {
                    return(buffer);
                }
                request.PageToken = response.NextPageToken;
                if (!String.IsNullOrEmpty(lastId))
                {
                    foreach (Message mes in messages)
                    {
                        if (mes.Id == lastId)
                        {
                            return(buffer);
                        }
                        buffer.Push(mes.Id);
                        ++allMessages;
                    }
                }
                else
                {
                    foreach (Message mes in messages)
                    {
                        buffer.Push(mes.Id);
                        ++allMessages;
                    }
                }
            } while (!String.IsNullOrEmpty(request.PageToken));
            return(buffer);
        }
示例#11
0
        public string?ExtractEmailSnippetContent(GmailRequest request)
        {
            UsersResource.MessagesResource.ListRequest listRequest = _gmailService.Users.Messages.List("me");
            listRequest.Q = request.Query;

            var response = listRequest.Execute();

            if (response.Messages == null)
            {
                return(null);
            }

            var messages = new List <Message>();

            foreach (var message in response.Messages)
            {
                UsersResource.MessagesResource.GetRequest msgRequest = _gmailService.Users.Messages.Get("me", message.Id);
                messages.Add(msgRequest.Execute());
            }

            var authMessage = messages
                              .Where(m => m.InternalDate >= request.NewerThan?.ToUnixTimeMilliseconds())
                              .OrderByDescending(m => m.InternalDate)
                              .FirstOrDefault();

            if (authMessage == null)
            {
                return(null);
            }

            if (request.SnippetRegex == null)
            {
                return(null);
            }

            var matches = request.SnippetRegex.Matches(authMessage.Snippet);

            if (matches.Any() && matches[0].Groups.Count > 1)
            {
                return(matches[0].Groups[1].Value);
            }

            return(null);
        }
示例#12
0
        /// <summary>
        /// List all Messages of the user's mailbox matching the query.
        /// </summary>
        /// <param name="service">Gmail API service instance.</param>
        /// <param name="userId">User's email address. The special value "me"
        /// can be used to indicate the authenticated user.</param>
        /// <param name="query">String used to filter Messages returned.</param>
        private void ListMessages(String query)
        {
            UsersResource.MessagesResource.ListRequest request = gs.Users.Messages.List("me");
            request.Q = query;

            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    Messages.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));
        }
示例#13
0
        //Mail important
        public List<MesImportant> getMesImportant(UserCredential credential)
        {
            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });
            //get Message id and threadid
            List<Message> resultMes = new List<Message>();
            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
            request.LabelIds = "INBOX";
            request.LabelIds = "IMPORTANT";
            ListMessagesResponse response = request.Execute();
            resultMes.AddRange(response.Messages);
            request.PageToken = response.NextPageToken;

            //get Detail Message
            List<Message> resultDetail = new List<Message>();
            foreach (var item in resultMes)
            {
                Message mes = new Message();
                Message mesd = service.Users.Messages.Get("me", item.Id).Execute();
                mes.Snippet = mesd.Snippet;
                mes.Id = mesd.Id;
                mes.LabelIds = mesd.LabelIds;
                mes.Payload = mesd.Payload;
                resultDetail.Add(mes);
            }

            List<MesImportant> mesLHeader = new List<MesImportant>();

            foreach (Message itemmes in resultDetail)
            {
                MesImportant mes = new MesImportant();
                mes.idimportant = itemmes.Id;
                mesLHeader.Add(mes);
            }

            return mesLHeader;
        }
示例#14
0
        /// <summary>
        /// Tries once to get all unread mail messages.
        /// <para>This method does not print information to the console.</para>
        /// <para>This method will throw exceptions if the list request fails.</para>
        /// </summary>
        /// <returns>The list with the unread mail messages</returns>
        public static List <RecievedMail> GetAllUnreadMails()
        {
            LastRead = Program.Time;
            List <RecievedMail> mails = new List <RecievedMail>(32);

            UsersResource.MessagesResource.ListRequest request = Account.service.Users.Messages.List("me");
            request.Q = "is:unread in:inbox";
            ListMessagesResponse response = request.Execute();

            if (response != null && response.Messages != null)
            {
                for (int i = 0; i < response.Messages.Count; i++)
                {
                    mails.Add(new RecievedMail(response.Messages[i].Id));
                }
            }

            LastRead            = Program.Time;
            LastSuccessfullRead = LastRead;
            return(mails);
        }
示例#15
0
    //Obtiene una lista de mensajes, los cuales solo contienen la ID
    public static List <Message> ListMessages(GmailService service, String userId, int maxMessages, string[] labels = null)
    {
        List <Message> result = new List <Message>();

        UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
        if (request != null)
        {
            request.MaxResults = maxMessages;
            if (labels != null)
            {
                request.LabelIds = labels;
            }
            ListMessagesResponse response = request.Execute();
            if (response.Messages == null)
            {
                return(null);
            }
            result.AddRange(response.Messages);
            return(result);
        }
        return(null);
    }
示例#16
0
        /// <summary>
        /// Receives truncated version of inbox with only message headers
        /// </summary>
        /// <returns></returns>
        private List <Message> GetReferenceInbox()
        {
            List <Message> referenceInbox = new List <Message>();

            //Creates request for page of inbox
            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(UserID);
            ListMessagesResponse response;

            int count = 1;

            do
            {
                try
                {
                    //Executes request for first page of inbox
                    response = request.Execute();

                    //Loop through each email in request
                    foreach (var email in response.Messages)
                    {
                        Console.WriteLine(count + ": " + email.Id);

                        referenceInbox.Add(email);

                        count++;
                    }

                    //Gets token for next page request
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
                //Keep looping till out of pages
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(referenceInbox);
        }
示例#17
0
        public static List <Message> ListMessages(GmailService service, String userId, String query)
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            request.Q = query;

            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    foreach (var item in response.Messages)
                    {
                        var msg     = GetMessage(service, userId, item.Id);
                        var headers = msg.Payload.Headers;
                        Console.WriteLine(GetHeader(headers, "From"));
                        // Console.WriteLine(GetHeader(headers, "To"));
                        Console.WriteLine(GetHeader(headers, "Date"));
                        Console.WriteLine(GetHeader(headers, "Subject"));

                        if (msg.Payload.MimeType == "text/plain")
                        {
                            byte[] data          = Convert.FromBase64String(msg.Payload.Body.Data);
                            string decodedString = Encoding.UTF8.GetString(data);
                            Console.WriteLine(decodedString);
                        }
                    }
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#18
0
        public static List <Message> ListMessages()
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
            request.Q = "in:inbox";
            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    return(result);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
        /// <summary>
        /// get all message
        /// </summary>
        /// <param name="service"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static List <Message> GetListOfAllMessages(GmailService service, string emailFolder)
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
            request.LabelIds = emailFolder;
            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#20
0
        /// <summary>
        /// Object that contains: List of messages, Token to retrieve the next page of results in the list and Estimated total number of results.
        /// </summary>
        /// <param name="userId">The user's email address. The special value "me" can be used to indicate the authenticated user.</param>
        /// <param name="includeSpamTrash">Include messages from SPAM and TRASH in the results. (Default: false)</param>
        /// <param name="labelIds">Only return messages with labels that match all of the specified label IDs.</param>
        /// <param name="maxResults">Maximum number of messages to return.</param>
        /// <param name="pageToken">Page token to retrieve a specific page of results in the list.</param>
        /// <param name="query">Only return messages matching the specified query. Supports the same query format as the Gmail search box. For example, "from:[email protected] rfc822msgid:<*****@*****.**> is:unread". Parameter cannot be used when accessing the api using the gmail.metadata scope.</param>
        /// <returns></returns>
        public ListMessagesResponse ListMessages(bool?includeSpamTrash = null, IEnumerable <string> labelIds = null, int?maxResults = null, string pageToken = null, String query = null)
        {
            ListMessagesResponse response = null;

            UsersResource.MessagesResource.ListRequest request = GmailService.Users.Messages.List("me");
            request.Q = query == null ? null : query;
            request.IncludeSpamTrash = includeSpamTrash == null ? false : includeSpamTrash;
            request.LabelIds         = labelIds == null ? null : new Google.Apis.Util.Repeatable <string>(labelIds);
            request.MaxResults       = maxResults == null ? null : maxResults;
            request.PageToken        = pageToken == null ? null : pageToken;

            try
            {
                response = request.Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }

            return(response);
        }
        public void run()
        {
            ServiceAccountCredential serviceCred;

            String serviceEmail = "*****@*****.**";
            String userEmail    = "*****@*****.**";
            String ryanEmail    = "*****@*****.**";

            using (var stream =
                       new FileStream("service_account.json", FileMode.Open, FileAccess.Read))
            {
                var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);

                serviceCred = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceEmail)
                {
                    Scopes = scopes,
                    User   = userEmail
                }.FromCertificate(certificate));
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = serviceCred,
                ApplicationName       = ApplicationName
            });

            // Define parameters of request.
            UsersResource.MessagesResource.ListRequest getReq = service.Users.Messages.List("me");;
            IList <Message> messages = getReq.Execute().Messages;

            Console.WriteLine("$ $ $ $\n = Messages received:\n");
            foreach (Message message in messages)
            {
                Console.WriteLine(message.ToString());
            }
            Console.Read();
        }
示例#22
0
        public List <Message> GetList()
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = _service.Users.Messages.List("me");
            request.Q = "from:([email protected]) label:[YOUR_GMAIL_LABEL_FOR_TRADINGVIEW_EMAILS] is:unread";

            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#23
0
        /// List all Messages of the user's mailbox matching the query.
        /// </summary>
        /// <param name="service">Gmail API service instance.</param>
        /// <param name="userId">User's email address. The special value "me"
        /// can be used to indicate the authenticated user.</param>
        /// <param name="query">String used to filter Messages returned.</param>
        private List <Message> ListMessages(GmailService service, String userId, String query)
        {
            List <Message> result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            // request.Fields = "nextPageToken, files(id,payload)"; //这个地方目前加了筛选规则还有问题 需要进一步研究
            //  request.Q = query;
            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#24
0
        public IList <Message> GetBandejaPorAsunto(string Asunto)
        {
            UserCredential Credential;

            using (var stream = new FileStream("client_secret_instalado.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                Credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    scopes, "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = Credential,
                ApplicationName       = ApplicationName
            });

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
            request.Q = Asunto; // subject:(Solicitud automática de nuevo asunto con el despacho) is:unread"
            IList <Message> _result    = request.Execute().Messages;
            List <Message>  _resultado = new List <Message>();

            if (_result != null && _result.Count > 0)
            {
                foreach (Message msj in _result)
                {
                    UsersResource.MessagesResource.GetRequest peticion = service.Users.Messages.Get("me", msj.Id);
                    peticion.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
                    var elementos = peticion.Execute();
                    _resultado.Add(elementos);
                }
                return(_resultado);
            }
            return(null);
        }
示例#25
0
        // API Request to get Email and Email Metadata
        public List <Message> GetRawEmails(string processedLabel)
        {
            List <Message> messageDataItems = new List <Message>();

            //Execute get email API request and save to list
            try
            {
                //Format a request to pull email id's
                UsersResource.MessagesResource.ListRequest emailListRequest = Connection.Users.Messages.List("me");

                //Add label to request
                emailListRequest.LabelIds = processedLabel;

                IList <Message> messages = emailListRequest.Execute().Messages;
                if (messages != null && messages.Count > 0)
                {
                    foreach (var message in messages)
                    {
                        //Format a new request to get email metadata
                        var emailInfoRequest = Connection.Users.Messages.Get("me", message.Id);

                        //Execute request for email metadata and add to list
                        Message emailData = emailInfoRequest.Execute();
                        messageDataItems.Add(emailData);
                    }
                    return(messageDataItems);
                }
            }
            catch (Exception e)
            {
                _log.LogInformation("Error when trying to get emails");
                _log.LogInformation(e.Message);
            }

            return(messageDataItems);
        }
        public List <Message> ListMessages(GmailService service, String userId, String query)
        {
            var result = new List <Message>();

            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
            request.Q = query;
            do
            {
                try
                {
                    ListMessagesResponse response = request.Execute();
                    result.AddRange(response.Messages);
                    request.PageToken = response.NextPageToken;
                }
                catch (Exception e)
                {
                    string[] tokens = e.Message.Split('.');
                    if (tokens[0].Equals("An error occurred while sending the request"))
                    {
                        MessageBox.Show(@"Please Check your internet Connection. Could not seed request");
                    }
                    else if (tokens[0].Equals("Google"))
                    {
                        DeleteFile(userId);
                        MessageBox.Show(@"The provided email address and sign in email address in browser are not same. Please sign in with provided email address. and Try again");
                    }
                    else
                    {
                        DeleteFile(userId);
                        MessageBox.Show(@"Some problem occured while connecting with requested account please try again");
                    }
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(result);
        }
示例#27
0
        public IList <MailMessage> getUnreadEmails()
        {
            // The list of messages that we're going to return
            IList <MailMessage> result = new List <MailMessage>();

            // First we need to find the ID of the UNREAD label, which we'll use
            // to select all of the unread messages.
            GmailService service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = getGmailCred()
            });
            IList <Label> labels = service.Users.Labels.List(ProudSourceEmail).Execute().Labels;

            string unreadID = "";

            foreach (Label l in labels)
            {
                if (l.Name == "UNREAD")
                {
                    unreadID = l.Id;
                }
            }

            // This should be impossible, because UNREAD is a system label
            // rather than a user label
            if (unreadID == "")
            {
                throw new Exception();
            }

            // And now we see what messages we have.
            UsersResource.MessagesResource.ListRequest listRequest = service.Users.Messages.List(ProudSourceEmail);
            // We specify that we only want unread messages
            listRequest.LabelIds = unreadID;

            IList <Message> messages = listRequest.Execute().Messages;

            // Now we get the full messages, and add them to a list
            foreach (Message message in messages)
            {
                // We have to get each email -- we've only listed them up until this point
                result.Add(getEmail(message.Id)); UsersResource.MessagesResource.GetRequest getReq = new UsersResource.MessagesResource.GetRequest(service, "me", message.Id);
                getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;

                Message     fullMessage    = getReq.Execute();
                MailMessage decodedMessage = convertToMailMessage(fullMessage);

                // Now we mark the message as read
                ModifyMessageRequest modMessageReq = new ModifyMessageRequest();
                // Because of the request parameters, we neeed to make a list.
                IList <string> labelIDs = new List <string>(); labelIDs.Add(unreadID);
                // We tell the request what labels we want to remove
                modMessageReq.RemoveLabelIds = labelIDs;
                // And execute
                //service.Users.Messages.Modify(modMessageReq, ProudSourceEmail, fullMessage.Id).Execute();

                result.Add(decodedMessage);
            }

            return(result);
        }
示例#28
0
        private string performSearchTask(BackgroundWorker worker, DoWorkEventArgs e)
        {
            var            client = new HaveIBeenPwnedRestClient();
            UserCredential credential;

            //We open the oauth setting of this app and request with browser your consent (only first time)
            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/GHBP.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

                        // Create Gmail API service.
                        var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            UsersResource.MessagesResource.ListRequest lRequest = service.Users.Messages.List(this.textBox4.Text);
            lRequest.LabelIds         = this.textBox1.Text;
            lRequest.IncludeSpamTrash = this.checkBox1.Checked;
            lRequest.Q = this.textBox3.Text;
            //list of total messages coming from the query filter
            List <Google.Apis.Gmail.v1.Data.Message> result = new List <Google.Apis.Gmail.v1.Data.Message>();
            //Distinct List of Senders
            Hashtable distinctSenders = new Hashtable();

            do
            {
                try
                {
                    //Gmail service does not give all the messages in one shot, so we have to perfom multiple request
                    //using pagination.
                    ListMessagesResponse response = lRequest.Execute();
                    result.AddRange(response.Messages);
                    lRequest.PageToken = response.NextPageToken;
                }
                catch (Exception excp)
                {
                    worker.ReportProgress(0, "An error occurred: " + excp.Message);
                }
            } while (!String.IsNullOrEmpty(lRequest.PageToken));

            IList <MessagePartHeader> tempHeader = null;
            string emailToCheck      = String.Empty;
            int    processedMessages = 0;
            int    totalMessages     = 0;
            int    maxRecords        = System.Convert.ToInt32(this.numericUpDown1.Value);

            if (result != null && result.Count > 0)
            {
                totalMessages = result.Count;
                foreach (var messageItem in result)
                {
                    System.Threading.Thread.Sleep(50);
                    var emailInfoRequest = service.Users.Messages.Get(this.textBox4.Text, messageItem.Id);
                    //Gmail service gives us only the message Id for each message we need another call to have the
                    // other fields , in particular the headers
                    var emailInfoResponse = emailInfoRequest.Execute();

                    if (emailInfoResponse != null)
                    {
                        tempHeader = emailInfoResponse.Payload.Headers;
                        foreach (MessagePartHeader mParts in tempHeader.Where(x => x.Name == this.textBox2.Text).ToList())
                        {
                            emailToCheck = ExtractString(mParts.Value);
                            //here we build the list of distinct senders
                            if (!distinctSenders.ContainsKey(emailToCheck))
                            {
                                distinctSenders.Add(emailToCheck, null);
                            }
                        }
                        processedMessages++;
                        worker.ReportProgress(processedMessages / totalMessages, "Processed " + processedMessages + " of " + totalMessages + " total messages");

                        if (processedMessages >= maxRecords)
                        {
                            //we stop the execution if we reached the max amount of messages defined into the config
                            break;
                        }
                    }
                }
                int totalSenders     = 0;
                int processedSenders = 0;

                using (var fw = new StreamWriter("GHBP_export.txt", true))
                {
                    if (distinctSenders.Count > 0)
                    {
                        totalSenders = distinctSenders.Count;
                        foreach (var item in distinctSenders.Keys)
                        {
                            List <Breach> response = null;
                            try
                            {
                                response = client.GetAccountBreaches(item.ToString()).Result;
                            }
                            catch (Exception excp)
                            {
                                //try to wait more if we hit an exception
                                System.Threading.Thread.Sleep(5000);
                            }
                            if (response != null && response.Count > 0)
                            {
                                fw.WriteLine(item);

                                Console.WriteLine(" ");
                            }
                            //To avoid breaking api request limit of 1 request every 1.5 seconds
                            System.Threading.Thread.Sleep(2000);
                            processedSenders++;
                            worker.ReportProgress(processedSenders / totalSenders, "This sender has been pwned: " + item + " - Processed " + processedSenders + " of " + totalSenders + " total senders");
                        }
                    }
                }
            }
            else
            {
                worker.ReportProgress(10000, "No messages found");
            }


            return("Ok");
        }
示例#29
0
        public static void email(String userId)
        {
            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.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            UsersResource.MessagesResource.ListRequest messagesListRequest =
                service.Users.Messages.List("*****@*****.**");

            // List labels.
            IList <Message> messageIDs = messagesListRequest.Execute().Messages;

            Database      db      = new Database("database");
            List <string> knownID = db.getEmailIds();

            foreach (Message messageID in messageIDs)
            {
                if (!knownID.Contains(messageID.Id))
                {
                    String decodedString = "";
                    UsersResource.MessagesResource.GetRequest preMessage =
                        service.Users.Messages.Get(userID, messageID.Id);
                    preMessage.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
                    Message message      = preMessage.Execute();
                    string  base64proper = message.Payload.Parts[0].Body.Data;
                    base64proper = base64proper.Replace('-', '+');
                    base64proper = base64proper.Replace('_', '/');

                    byte[] data      = Convert.FromBase64String(base64proper);
                    string rawData   = Encoding.UTF8.GetString(data);
                    string posSender = "";
                    foreach (MessagePartHeader header in message.Payload.Headers)
                    {
                        if (header.Name == "From")
                        {
                            posSender = header.Value;
                            break;
                        }
                    }
                    List <string> companies = db.getCompanyNames();
                    string        sender    = "Unknown";

                    foreach (string company_name in companies)
                    {
                        Regex regex = new Regex(company_name.ToLower());
                        if (regex.IsMatch(posSender.ToLower()) || regex.IsMatch(rawData.ToLower()))
                        {
                            sender = company_name;
                        }
                    }

                    long?internalDate = message.InternalDate;  //Put in database

                    db.newEmail(messageID.Id, sender, internalDate, categoriseEmail(rawData));
                    Console.WriteLine("");
                }
            }
        }
        public async Task <PollingDataDTO> Poll(PollingDataDTO pollingData)
        {
            Logger.Info($"Polling for Gmail was launched {pollingData.ExternalAccountId}");

            var serv            = new GoogleGmail();
            var googleAuthToken = JsonConvert.DeserializeObject <GoogleAuthDTO>(pollingData.AuthToken);
            var service         = await serv.CreateGmailService(googleAuthToken);

            if (string.IsNullOrEmpty(pollingData.Payload))
            {
                //Polling is called for the first time
                //we have no history id to synchronise partitially, so we request the last message from the inbox
                UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(pollingData.ExternalAccountId);
                request.RequestParameters["maxResults"] = new Parameter()
                {
                    DefaultValue = "1", Name = "maxResults", ParameterType = "query"
                };
                var list = request.Execute();

                //then we have to get its details and historyId (to use with history listing API method)

                pollingData.Payload = GetHistoryId(service, list.Messages.FirstOrDefault().Id, pollingData.ExternalAccountId);
                Logger.Info($"Polling for Gmail {pollingData.ExternalAccountId}: remembered the last email in the inbox");
            }
            else
            {
                var request = service.Users.History.List(pollingData.ExternalAccountId);
                request.StartHistoryId = ulong.Parse(pollingData.Payload);
                var result = request.Execute();
                Logger.Info($"Polling for Gmail {pollingData.ExternalAccountId}: received a history of changes");
                if (result.History != null)
                {
                    foreach (var historyRecord in result.History)
                    {
                        if (historyRecord.MessagesAdded != null)
                        {
                            foreach (var mail in historyRecord.MessagesAdded.Reverse())
                            {
                                //TODO: make a batch request for emails, instead of calling one by one
                                var email = GetEmail(service, mail.Message.Id, pollingData.ExternalAccountId);
                                var eventReportContent = new EventReportCM
                                {
                                    EventNames        = "GmailInbox",
                                    EventPayload      = new CrateStorage(Crate.FromContent("GmailInbox", email)),
                                    Manufacturer      = "Google",
                                    ExternalAccountId = pollingData.ExternalAccountId
                                };

                                pollingData.Payload = email.MessageID;
                                Logger.Info("Polling for Gmail: got a new email, broadcasting an event to the Hub");
                                await _reporter.Broadcast(Crate.FromContent("Standard Event Report", eventReportContent));
                            }
                        }
                    }
                }
                else
                {
                    Logger.Info($"Polling for Gmail {pollingData.ExternalAccountId}: no new emails");
                }
            }
            pollingData.Result = true;
            return(pollingData);
        }