Exemplo n.º 1
0
        public async Task <bool> AddAttachmentAsync(EmailAttachmentDTO emailAttachmentDto)
        {
            this.context.EmailAttachments.Add(emailAttachmentDto.ToEntity());
            await this.context.SaveChangesAsync();

            return(true);
        }
 public EmailAttachmentViewModel(EmailAttachmentDTO attachment)
 {
     Id             = attachment.Id;
     ServerFileName = attachment.FileName;
     Title          = attachment.Title;
     ViewUrl        = UrlHelper.GetViewAttachmentUrl(Id);
 }
Exemplo n.º 3
0
 public static EmailAttachmentEntity ToEntity(this EmailAttachmentDTO dto)
 {
     return(dto != null
         ? new EmailAttachmentEntity
     {
         ReceivedEmailId = dto.ReceivedEmailId,
         AttachmentName = dto.AttachmentName,
         FileSizeInMb = dto.FileSizeInMb,
     }
         : null);
 }
Exemplo n.º 4
0
        public static void ValidatorAddAttachment(EmailAttachmentDTO attachmentDTO)
        {
            if (attachmentDTO.FileName.Length < 5 || attachmentDTO.FileName.Length > 100)
            {
                throw new EmailExeption("Lenght of name attachment is not correct!");
            }

            if (attachmentDTO.GmailId.Length < 5 || attachmentDTO.GmailId.Length > 100)
            {
                throw new EmailExeption("Lenght of GmailId is not correct!");
            }
        }
Exemplo n.º 5
0
        public void Insert(EmailAttachmentDTO attachment)
        {
            Add(new EmailAttachment()
            {
                EmailId  = attachment.EmailId,
                FileName = attachment.FileName,
                Path     = attachment.RelativePath,
                Title    = attachment.Title,

                CreateDate = attachment.CreateDate,
            });
            unitOfWork.Commit();
        }
Exemplo n.º 6
0
        public async Task AddAttachmentAsync(EmailAttachmentDTO attachmentDTO)
        {
            ValidatorEmailService.ValidatorAddAttachment(attachmentDTO);

            var gmaiId = await this.context.Emails
                         .FirstOrDefaultAsync(id => id.GmailId == attachmentDTO.GmailId);

            if (gmaiId == null)
            {
                var attachment = new EmailAttachment
                {
                    FileName = attachmentDTO.FileName,
                    SizeInKB = attachmentDTO.SizeInKB,
                    GmailId  = attachmentDTO.GmailId
                };

                await this.context.EmailAttachments.AddAsync(attachment);

                await this.context.SaveChangesAsync();
            }
        }
Exemplo n.º 7
0
        public async Task AddAttachment_Test()
        {
            var    gmailId  = "TestGmailId";
            var    FileName = "TestFileName";
            double fileSize = 876.77;

            var encodeDecodeServiceMock = new Mock <IEncodeDecodeService>().Object;
            var loggerMock = new Mock <ILogger <EmailService> >().Object;

            var options = TestUtilities.GetOptions(nameof(AddAttachment_Test));

            using (var actContext = new E_MailApplicationsManagerContext(options))
            {
                await actContext.EmailAttachments.AddAsync(
                    new EmailAttachment
                {
                    GmailId  = gmailId,
                    FileName = FileName,
                    SizeInKB = fileSize
                });

                await actContext.SaveChangesAsync();

                var ettachmentDto = new EmailAttachmentDTO
                {
                    FileName = FileName,
                    GmailId  = gmailId,
                    SizeInKB = fileSize
                };

                var sut    = new EmailService(actContext, loggerMock, encodeDecodeServiceMock);
                var result = sut.AddAttachmentAsync(ettachmentDto);

                Assert.IsNotNull(result);
            }
            using (var assertContext = new E_MailApplicationsManagerContext(options))
            {
                Assert.AreEqual(2, assertContext.EmailAttachments.Count());
            }
        }
Exemplo n.º 8
0
        public async Task ThrowExeptionWhenAddAttachmentNameIsMinLenght_Test()
        {
            var    gmailId  = "TestGmailId";
            var    FileName = "Test";
            double fileSize = 876.77;

            var encodeDecodeServiceMock = new Mock <IEncodeDecodeService>().Object;
            var loggerMock = new Mock <ILogger <EmailService> >().Object;

            var options = TestUtilities.GetOptions(nameof(ThrowExeptionWhenAddAttachmentNameIsMinLenght_Test));

            using (var actContext = new E_MailApplicationsManagerContext(options))
            {
                var ettachmentDto = new EmailAttachmentDTO
                {
                    FileName = FileName,
                    GmailId  = gmailId,
                    SizeInKB = fileSize
                };

                var sut = new EmailService(actContext, loggerMock, encodeDecodeServiceMock);
                await sut.AddAttachmentAsync(ettachmentDto);
            }
        }
        private IList <EmailAttachmentDTO> ProcessAttachments(IUnitOfWork db, MailMessage email, long emailId)
        {
            var results = new List <EmailAttachmentDTO>();

            var attachFolder = _settings.AttachmentFolderPath;
            var date         = DateHelper.GetAppNowTime();
            var dateDir      = string.Format("{0}_{1}_{2}", date.Month, date.Day, date.Year);

            var attachments = email.Attachments.Select(a => a);

            foreach (var attachment in attachments)
            {
                try
                {
#if DEBUG
                    attachFolder = "D:\\AmazonOutput\\EmailAttachments\\";
#endif
                    var filePath = AttachmentHelper.SaveMailAttachment(attachment, attachFolder, dateDir);
                    var filename = Path.GetFileName(filePath);
                    var attach   = new EmailAttachmentDTO()
                    {
                        EmailId      = emailId,
                        FileName     = filename,
                        Title        = attachment.Name,
                        PhysicalPath = filePath,
                        RelativePath = "~/" + dateDir + "/" + filename,
                        CreateDate   = date
                    };
                    db.EmailAttachments.Insert(attach);
                    results.Add(attach);
                }
                catch (Exception ex)
                {
                    _log.Error("Failed to save attachment " + attachment.Name + " for reason: " + ex);
                }
            }

            var alternateViews = email.AlternateViews.Where(a => a.ContentType?.MediaType == "image/jpeg").Select(a => a);
            foreach (var view in alternateViews)
            {
                try
                {
                    var filePath = AttachmentHelper.SaveMailAttachment(view, attachFolder, dateDir);
                    var filename = Path.GetFileName(filePath);
                    var attach   = new EmailAttachmentDTO()
                    {
                        EmailId      = emailId,
                        FileName     = filename,
                        Title        = view.ContentId,
                        PhysicalPath = filePath,
                        RelativePath = "~/" + dateDir + "/" + filename,
                        CreateDate   = date
                    };
                    db.EmailAttachments.Insert(attach);
                    results.Add(attach);
                }
                catch (Exception ex)
                {
                    _log.Error("Failed to save attachment " + view.ContentId + " for reason: " + ex);
                }
            }

            return(results);
        }
Exemplo n.º 10
0
        public async Task GetUnreadEmailsFromGmailAsync()
        {
            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);
            }

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

            var emailThreads = service.Users.Threads.List(SERVICE_ACCOUNT_EMAIL);

            // Get emails only form inbox which are unread
            var labels = new Google.Apis.Util.Repeatable <string>(new List <string> {
                "INBOX", "UNREAD"
            });

            emailThreads.LabelIds         = labels;
            emailThreads.IncludeSpamTrash = false;
            emailThreads.MaxResults       = 5000;

            var emailThreadResult = await emailThreads.ExecuteAsync();

            if (emailThreadResult != null && emailThreadResult.Threads != null && emailThreadResult.Threads.Any())
            {
                foreach (var thread in emailThreadResult.Threads)
                {
                    var data = await service.Users.Threads.Get(SERVICE_ACCOUNT_EMAIL, thread.Id).ExecuteAsync();

                    var gmailId = data?.Id;

                    if (data != null)
                    {
                        foreach (var emailInfoResponse in data.Messages)
                        {
                            if (emailInfoResponse != null)
                            {
                                string body = string.Empty;

                                var dateReceived =
                                    emailInfoResponse.Payload?.Headers?.FirstOrDefault(s => s.Name == "Date")?.Value ??
                                    string.Empty;
                                var from = emailInfoResponse.Payload?.Headers?.FirstOrDefault(s => s.Name == "From")
                                           ?.Value ?? string.Empty;
                                var subject =
                                    emailInfoResponse.Payload?.Headers?.FirstOrDefault(s => s.Name == "Subject")
                                    ?.Value ?? string.Empty;

                                var emailDto = new EmailDTO
                                {
                                    Subject      = subject,
                                    Body         = body,
                                    DateReceived = dateReceived,
                                    From         = from,
                                    GmailEmailId = gmailId,
                                };

                                var parts = emailInfoResponse.Payload?.Parts;

                                double totalAttachmentsSizeInMb = 0;
                                var    attachmentsToAdd         = new List <EmailAttachmentDTO>();

                                if (parts != null)
                                {
                                    if (parts.First().MimeType.Contains("text/plain")) // Email do not have attachments
                                    {
                                        emailDto.Body = parts.First().Body.Data;
                                        emailDto.AttachmentsTotalSizeInMB = 0;
                                        emailDto.TotalAttachments         = 0;
                                    }
                                    else // Email have attachment(s)
                                    {
                                        emailDto.Body = parts.First().Parts.First().Body.Data;

                                        var attachments = parts.Skip(1).ToList();

                                        foreach (var attachment in attachments)
                                        {
                                            var attachmentName = attachment.Filename;

                                            double attachmentSize;
                                            try
                                            {
                                                attachmentSize = double.Parse(attachment.Body.Size.ToString());
                                            }
                                            catch (Exception)
                                            {
                                                attachmentSize = 0.0;
                                            }

                                            var emailAttachmentDto = new EmailAttachmentDTO
                                            {
                                                FileSizeInMb   = attachmentSize,
                                                AttachmentName = attachmentName
                                            };

                                            totalAttachmentsSizeInMb += attachmentSize;

                                            attachmentsToAdd.Add(emailAttachmentDto);
                                        }

                                        totalAttachmentsSizeInMb         /= (1024 * 1024);
                                        emailDto.AttachmentsTotalSizeInMB = totalAttachmentsSizeInMb;
                                        emailDto.TotalAttachments         = attachments.Count;
                                    }
                                }

                                var id = await this.emailService.CreateAsync(emailDto);

                                if (attachmentsToAdd.Count > 0)
                                {
                                    foreach (var attachment in attachmentsToAdd)
                                    {
                                        attachment.ReceivedEmailId = id;
                                        await this.emailAttachmentService.AddAttachmentAsync(attachment);
                                    }
                                }

                                var markAsReadRequest = new ModifyThreadRequest {
                                    RemoveLabelIds = new[] { "UNREAD" }
                                };
                                await service.Users.Threads.Modify(markAsReadRequest, SERVICE_ACCOUNT_EMAIL, thread.Id)
                                .ExecuteAsync();
                            }
                        }
                    }
                }
            }
        }