コード例 #1
0
        public async Task <int> SyncEmails()
        {
            //Create a GmailService which crucial for accecing Gmail API.
            GmailService service = await this.GetServiceAsync();

            //Get all the messages from INBOX which are mark with UNREAD label.
            ListMessagesResponse emailListResponse = await GetNewEmailsAsync(service);

            if (emailListResponse != null && emailListResponse.Messages != null)
            {
                foreach (var email in emailListResponse.Messages)
                {
                    var emailInfoRequest = service.Users.Messages.Get(gmailAccountName, email.Id);

                    //After executeAsync we recieve one email with all his data and attachments.
                    var currentMessage = await emailInfoRequest.ExecuteAsync();

                    var emailDTO = this.messageToEmailDTOPmapper.MapToDTO(currentMessage);

                    await emailService.CreateAsync(emailDTO);

                    await this.MarkAsReadAsync(service, email.Id);
                }
                return(emailListResponse.Messages.Count);
            }
            return(0);
        }
コード例 #2
0
    public async Task <EmailServerPayload> CreateEmailServerAsync([Service] IEmailService service,
                                                                  CreateEmailServerInput input, CancellationToken cancellationToken)
    {
        var emailServer = input.Adapt <Data.Models.EmailServer>();

        emailServer.Id = emailServer.Id == default ? Guid.NewGuid() : emailServer.Id;
        await service.CreateAsync(emailServer, cancellationToken);

        return(input.Adapt <EmailServerPayload>());
    }
コード例 #3
0
        public async Task GmailAPI()
        {
            UserCredential credential = ApproveCredentialFromFile();

            GmailService gmailService = CreateGmailService(credential);

            var emailListRequest = gmailService.Users.Messages.List("*****@*****.**");

            emailListRequest.LabelIds         = "INBOX";
            emailListRequest.IncludeSpamTrash = false;

            var emailListResponse = emailListRequest.ExecuteAsync().Result;

            if (emailListResponse != null && emailListResponse.Messages != null)
            {
                foreach (var email in emailListResponse.Messages)
                {
                    var emailRequest = gmailService.Users.Messages.Get("*****@*****.**", email.Id);

                    Message emailFullResponse = emailRequest.ExecuteAsync().Result;

                    if (emailFullResponse != null)
                    {
                        string originalMailId = emailFullResponse.Id;

                        bool checkIfEmailIsInDB = await emailService.CheckIfEmailExists(originalMailId);

                        if (!checkIfEmailIsInDB && !emailFullResponse.LabelIds.Contains("CATEGORY_PROMOTIONS"))
                        {
                            GetEmailInformationByParts(emailFullResponse, out DateTime dateReceived, out string senderName, out string senderEmail, out string subject, out string body, out List <string> attachmentNames, out List <double> attachmentSizes);

                            var createdEmail = await emailService.CreateAsync(originalMailId, senderName, senderEmail, dateReceived, subject, body);

                            await this.attachmentsService.CreateAsync(createdEmail.Id, attachmentNames, attachmentSizes);
                        }
                    }
                }
            }

            gmailService.Dispose();
        }
コード例 #4
0
        public async Task SyncEmails()
        {
            UserCredential credential;

            using (var stream = new FileStream("credentials.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;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

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


            var emailListResponse = await GetNewEmails(service);

            if (emailListResponse != null && emailListResponse.Messages != null)
            {
                foreach (var email in emailListResponse.Messages)
                {
                    var emailInfoRequest = service.Users.Messages.Get("*****@*****.**", email.Id);

                    var emailInfoResponse = await emailInfoRequest.ExecuteAsync();


                    if (emailInfoResponse != null)
                    {
                        string dateRecieved = emailInfoResponse.Payload.Headers
                                              .FirstOrDefault(x => x.Name == "Date")
                                              .Value;

                        string sender = emailInfoResponse.Payload.Headers
                                        .FirstOrDefault(x => x.Name == "From")
                                        .Value;

                        //sender = ParseSender(sender);

                        string subject = emailInfoResponse.Payload.Headers
                                         .FirstOrDefault(x => x.Name == "Subject")
                                         .Value;

                        //Body
                        var str           = new StringBuilder();
                        var itemToResolve = emailInfoResponse.Payload.Parts[0];

                        if (itemToResolve.MimeType == "text/plain")
                        {
                            //str.Append(DecodeBody(itemToResolve));
                            str.Append(itemToResolve.Body.Data);
                        }
                        else
                        {
                            //str.Append(DecodeBody(itemToResolve.Parts[0]));
                            str.Append(itemToResolve.Parts[0].Body.Data);
                        }

                        //Body
                        string body = str.ToString();

                        ICollection <AttachmentDTO> attachmentsOfEmail = new List <AttachmentDTO>();

                        if (!(itemToResolve.MimeType == "text/plain"))
                        {
                            attachmentsOfEmail = ParseAttachments(emailInfoResponse);
                        }

                        var emailDTO = new EmailDTO
                        {
                            RecievingDateAtMailServer = dateRecieved,
                            Sender      = sender,
                            Subject     = subject,
                            Body        = body,
                            Attachments = attachmentsOfEmail,
                            Status      = EmailStatusesEnum.NotReviewed
                        };

                        await emailService.CreateAsync(emailDTO);
                    }
                }
            }
        }