Example #1
0
        async Task ProcessNewEmailAsync(IMessageSummary summary, CancellationToken ct)
        {
            var subject = summary.Envelope.Subject;

            logger.LogInformation("New Email arrived. subject: {0}, uid: {1}", subject, summary.UniqueId.Id);
            if (subject == null)
            {
                logger.LogInformation("Uid: {0} process failed, no subject.", summary.UniqueId.Id);
                return;
            }
            if (!(subject.Contains("操作系统") && subject.Contains("实验一")))
            {
                logger.LogInformation("Uid: {0} process failed, subject not match", summary.UniqueId.Id);
                return;
            }
            var student = Student.AllStudents.SingleOrDefault(
                s => subject.Contains(s.Name) ||
                summary.Envelope.From.Any(a => a.Name.Contains(s.Name)) ||
                summary.Attachments.Any(a => a.FileName.Contains(s.Name)));

            if (student == null)
            {
                logger.LogInformation("Uid: {0} process failed, no student found", summary.UniqueId.Id);
                return;
            }

            var attachmentMetadata = summary.Attachments.FirstOrDefault(a => KnownHomeworkExtensions.IsPathHasKnownExtension(a.FileName));

            if (attachmentMetadata == null)
            {
                logger.LogInformation("Uid: {0} process failed, no attachment found", summary.UniqueId.Id);
                return;
            }
            var attachment = (MimePart)await client.Inbox.GetBodyPartAsync(summary.UniqueId, attachmentMetadata, ct);

            Email email = new Email
            {
                EmailUID       = summary.UniqueId.Id,
                AttachmentName = attachment.FileName,
                SenderName     = student.Name,
                FromAddress    = summary.Envelope.From.OfType <MailboxAddress>().First().Address,
            };

            MemoryStream content = new MemoryStream();
            await attachment.Content.DecodeToAsync(content);

            content.Position     = 0;
            email.AttachmentSHA1 = sha1.ComputeHash(content);
            content.Position     = 0;
            if (options.AttachmentSavePath != null)
            {
                email.FileSavePath = Path.GetFullPath(Path.Combine(options.AttachmentSavePath, $"{student.StudentNumber}-{student.Name}{Path.GetExtension(attachment.FileName)}"));
                using (var file = File.OpenWrite(email.FileSavePath))
                {
                    content.CopyTo(file);
                }
            }
            context.Email.Add(email);
            await context.SaveChangesAsync();

            logger.LogInformation("Uid: {0} process success", summary.UniqueId.Id);
        }