コード例 #1
0
        public async Task ReturnAttchmentsType_Successfully()
        {
            var options = TestUtils.GetOptions(nameof(ReturnAttchmentsType_Successfully));

            var testAttachmentId = "Attachment";

            var newAttachment = new EmailAttachments()
            {
                Id = testAttachmentId
            };

            using (var arrangeContext = new EmailManagerDbContext(options))
            {
                await arrangeContext.EmailAttachments.AddAsync(newAttachment);

                await arrangeContext.SaveChangesAsync();
            }

            using (var assertContext = new EmailManagerDbContext(options))
            {
                var sut    = new AttachmentsService(assertContext);
                var result = await sut.GetEmailAttachmentsByEmailIdAsync(testAttachmentId);

                Assert.IsInstanceOfType(result, typeof(ICollection <EmailAttachmentsDTO>));
            }
        }
コード例 #2
0
 public void AddAttachment(EmailAttachmentMetaData MessageAttachment)
 {
     if (EmailAttachments == null)
     {
         EmailAttachments = new List <EmailAttachmentMetaData>();
     }
     EmailAttachments.Add(MessageAttachment);
 }
コード例 #3
0
        public static async Task SeedAttachments(this IApplicationBuilder appBuilder)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException(nameof(appBuilder));
            }

            var logFactory             = (ILogFactory)appBuilder.ApplicationServices.GetService(typeof(ILogFactory));
            var emailClient            = (IEmailJobClient)appBuilder.ApplicationServices.GetService(typeof(IEmailJobClient));
            var attachmentsSeedService = (IAttachmentsSeedService)appBuilder.ApplicationServices.GetService(typeof(IAttachmentsSeedService));

            var log = logFactory.CreateLog(new SeedAttachmentsAppbuilder());
            var attachmentsSeedDto = await attachmentsSeedService.GetFirstAsync().ConfigureAwait(false);

            if (!attachmentsSeedDto.IsSeeded)
            {
                try
                {
                    log.Info($"Seed attachments files");
                    var attachmentsToSeed = EmailAttachments.GetOnboardingAttachments();
                    foreach (var attachment in attachmentsToSeed)
                    {
                        try
                        {
                            await emailClient.StorageApi
                            .AddFileAsync(new FileSpecModel
                            {
                                FileName = attachment.FileName,
                                Content  = Convert.ToBase64String(attachment.GetContent())
                            })
                            .ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex, $"Seed failed for file name: {attachment.FileName}. Exception message: {ex.Message}");
                            throw;
                        }
                    }

                    attachmentsSeedDto.IsSeeded = true;
                    attachmentsSeedDto.SeededOn = DateTime.UtcNow;
                    await attachmentsSeedService.UpdateAsync(attachmentsSeedDto).ConfigureAwait(false);
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    log.Error(ex, $"Attachments seed failed. Exception message: {ex.Message}");
                }
            }
        }
コード例 #4
0
        public async Task CreateAsync(string emailId, List <string> attachmentNames, List <double> attachmentSizes)
        {
            for (int i = 0; i < attachmentNames.Count; i++)
            {
                var newAttachment = new EmailAttachments
                {
                    FileName = attachmentNames[i],
                    FileSize = attachmentSizes[i],
                    EmailId  = emailId
                };

                this.context.EmailAttachments.Add(newAttachment);
            }
            await this.context.SaveChangesAsync();
        }
コード例 #5
0
        public static EmailAttachmentsDTO ToDTO(this EmailAttachments entity)
        {
            if (entity is null)
            {
                return(null);
            }

            var emailAttachment = new EmailAttachmentsDTO
            {
                Id       = entity.Id,
                EmailId  = entity.EmailId,
                FileName = entity.FileName,
                FileSize = entity.FileSize
            };

            return(emailAttachment);
        }
コード例 #6
0
        public EmailNotificationSettings(EmailTarget fromSender, EmailTarget toSender, string subject, string htmlContent, List <dynamic> attachments)
        {
            _to          = toSender.Email;
            _from        = fromSender.Email;
            _senderName  = fromSender.Name;
            _subject     = subject;
            _ccEmails    = new List <EmailTarget>();
            _bccEmails   = new List <EmailTarget>();
            _htmlContent = htmlContent;

            if (attachments != null)
            {
                foreach (var item in attachments)
                {
                    EmailAttachment attachment = new EmailAttachment();
                    fileStream = new MemoryStream();
                    item.FileStream.CopyTo(fileStream);
                    attachment.FileName       = item.FileName;
                    attachment.FileStreamJson = JsonConvert.SerializeObject(fileStream, Formatting.Indented, new MemoryStreamJsonConverter());
                    EmailAttachments.Add(attachment);
                }
            }
        }
コード例 #7
0
        private void Process_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.lfcFirma.CBoxSelectedValue != null)
                {
                    using (var db = new SteinbachEntities())
                    {
                        CRMEmail mail = new CRMEmail();
                        mail.created = DateTime.Now;



                        foreach (var item in Attachments)
                        {
                            EmailAttachments Attach = new EmailAttachments();
                            Attach.CRMEmails      = mail;
                            Attach.Filename       = item.Key;
                            Attach.Path           = item.Value.Path;
                            Attach.created        = DateTime.Now;
                            Attach.AttachmentType = item.Value.AttachmentType;
                            Attach.isEmbedded     = item.Value.isEmbedded == true ? (short)1 : (short)0;

                            db.AddToEmailAttachments(Attach);
                        }


                        mail.EntryID        = oMailItem.EntryID;
                        mail.ConversationID = oMailItem.ConversationID;
                        mail.Betreff        = oMailItem.Subject;
                        mail.Absender       = oMailItem.SenderName;
                        var session = oMailItem.Session;
                        mail.Typ = oMailItem.SenderEmailType;
                        switch (oMailItem.BodyFormat)
                        {
                        case Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML:
                        {
                            mail.BodyFormat = "HTML";
                            if (html != "")
                            {
                                mail.HTMLText = html;
                            }
                            else
                            {
                                mail.HTMLText = oMailItem.HTMLBody;
                            }

                            mail.Text = oMailItem.Body;
                            break;
                        }

                        case Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatPlain:
                        {
                            mail.BodyFormat = "PLAIN";
                            mail.Text       = oMailItem.Body;
                            break;
                        }

                        case Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText:
                        {
                            mail.BodyFormat = "RichText";
                            mail.RTF_Text   = oMailItem.RTFBody;
                            mail.Text       = oMailItem.Body;
                            break;
                        }

                        case Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatUnspecified:
                        {
                            mail.BodyFormat = "Unspecified";
                            mail.Text       = oMailItem.Body;
                            break;
                        }

                        default:
                            break;
                        }



                        mail.OutlookUsername = session.CurrentUser.Name;
                        //var user = GetActiveUser();
                        //if (user != null)
                        //{
                        //    if (user.isActive)
                        //    {
                        //        mail.id_PersonSI = user.id;
                        //    }

                        //}
                        mail.AbsenderMailAdresse = oMailItem.SenderEmailAddress;
                        mail.Datum = oMailItem.ReceivedTime;


                        mail.Empfaenger      = oMailItem.ReceivedByName;
                        mail.Empfaengerliste = oMailItem.To;
                        mail.id_Firma        = (int)lfcFirma.CBoxSelectedValue;

                        if (lfcStatus.CBoxSelectedValue != null)
                        {
                            mail.Status = (int)lfcStatus.CBoxSelectedValue;
                        }

                        if (lfcAktion.CBoxSelectedValue != null)
                        {
                            mail.Aktion = (int)lfcAktion.CBoxSelectedValue;
                        }

                        if (lfcKontakt.CBoxSelectedValue != null)
                        {
                            mail.id_Kontakt = (int)lfcKontakt.CBoxSelectedValue;
                        }



                        db.AddToCRMEmails(mail);
                        db.SaveChanges();
                        // SaveAttachment(oMailItem, mail.id);

                        // this.Close();

                        PlayStoryboard();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Email konnte nicht zugeordnet werden." + "-" + ex.Message);
            }
        }
コード例 #8
0
        /// <summary>
        /// Sends the notification.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <param name="alarm">The alarm.</param>
        /// <param name="globalProperties">The global properties.</param>
        /// <param name="notifications">The notifications.</param>
        /// <returns></returns>
        public bool SendNotification(BizTalkEnvironment environment, Common.Alarm alarm, string globalProperties, Dictionary <MonitorGroupTypeName, MonitorGroupData> notifications)
        {
            try
            {
                LoggingHelper.Info("DESCRIPTION " + alarm.Description);
                XDocument globalDocument = XDocument.Parse(globalProperties);
                XDocument alarmDocument  = XDocument.Parse(alarm.AlarmProperties);

                //Read configured properties
                XNamespace bsd              = XNamespace.Get("http://www.biztalk360.com/alarms/notification/basetypes");
                string     email            = string.Empty;
                string     emailTo          = string.Empty;
                string     ccEmail          = string.Empty;
                string     upAlert          = string.Empty;
                string     autoCorrectAlert = string.Empty;

                //Global Properties
                XDocument globalProps = XDocument.Load(new StringReader(globalProperties));

                foreach (XElement element in globalProps.Descendants(bsd + "TextArea"))
                {
                    XAttribute xAttribute = element.Attribute("Name");
                    if (element.Attribute("Name").Value == "Email-To")
                    {
                        emailTo = element.Attribute("Value").Value;
                    }
                    if (element.Attribute("Name").Value == "C-C")
                    {
                        ccEmail = element.Attribute("Value").Value;
                    }
                    if (element.Attribute("Name").Value == "Up-Alert")
                    {
                        upAlert = element.Attribute("Value").Value;
                    }
                    if (element.Attribute("Name").Value == "AutoCorrect-Alert")
                    {
                        autoCorrectAlert = element.Attribute("Value").Value;
                    }
                }
                bool useEmailTo = Convert.ToBoolean(globalDocument.XPathSelectElement(
                                                        "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'CheckBox' and @Name = 'use-Email-To']")
                                                    ?.Attribute("Value")?.Value);

                BT360Helper helper = new BT360Helper(notifications, environment, alarm, MessageType.ConsolidatedMessage, MessageFormat.Text);

                EmailMessageBody emailMessageBody = (EmailMessageBody)helper.ConvertDictionaryToObject <EmailMessageBody>(alarm.AdditionalProperties, SMTPConfigurationInfo.EmailMessageBody);
                EmailAttachments emailAttachments = (EmailAttachments)helper.ConvertDictionaryToObject <EmailAttachments>(alarm.AdditionalProperties, SMTPConfigurationInfo.EmailAttachments);
                SMTPSetting      smtpSetting      = (SMTPSetting)helper.ConvertDictionaryToObject <SMTPSetting>(alarm.AdditionalProperties, SMTPConfigurationInfo.SMTPSetting);
                if (smtpSetting == null)
                {
                    throw new Exception("SMTP Setting is not present in the database. Please use the UI to update the correct setting.");
                }

                //When installed first time, these values will be blank
                if (smtpSetting.serverName == "" || smtpSetting.adminEmailAddress == "")
                {
                    //SK: 4th Feb 2012, replaced returning null with exception, since we can't proceed further.
                    throw new Exception("SMTP Setting is not configured (admin email or server name is blank). Please use the UI to update the correct setting.");
                    //return null;
                }
                switch (emailMessageBody.notificationType)
                {
                case NotificationType.UpAlert:
                    if (upAlert != "" && useEmailTo)
                    {
                        email = upAlert;
                    }
                    else
                    {
                        email = emailTo;
                    }
                    break;

                case NotificationType.AutoCorrectAlert:
                    if (autoCorrectAlert != "" && useEmailTo)
                    {
                        email = autoCorrectAlert;
                    }
                    else
                    {
                        email = emailTo;
                    }
                    break;

                default:
                    email = emailTo;
                    break;
                }

                string strFrom    = emailMessageBody.fromEmailAddress;
                string strName    = emailMessageBody.fromDisplayName;
                string strTo      = email;
                string strCC      = ccEmail;
                string strSubject = emailMessageBody.subject;
                string strBody    = emailMessageBody.xmlData;
                LoggingHelper.Info("SUBJECT " + strSubject);
                try
                {
                    SmtpClient smtp = new SmtpClient();

                    smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtp.Host                  = smtpSetting.serverName;
                    smtp.Port                  = Convert.ToInt32(smtpSetting.port);
                    smtp.EnableSsl             = (smtpSetting.sslMode == SMTPSSLMode.DedicatedSSLPort) ? true : false;
                    smtp.UseDefaultCredentials = (smtpSetting.authentication == SMTPAuthentication.IntegratedWindowsAuthOverNtlm) ? true : false;
                    smtp.Credentials           = (smtpSetting.authentication == SMTPAuthentication.Anonymous) ? null : new NetworkCredential(smtpSetting.userName, smtpSetting.password);

                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                    string      htmlData    = Helper.TransformXMLToHTML(emailMessageBody.xslt, emailMessageBody.xmlData);
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From       = new MailAddress(strFrom, strName);
                    mailMessage.Subject    = strSubject;
                    mailMessage.Body       = htmlData;
                    mailMessage.IsBodyHtml = true;
                    //Adding multiple To Addresses
                    foreach (string sTo in strTo.Split(";".ToCharArray()))
                    {
                        mailMessage.To.Add(sTo);
                    }

                    //Adding multiple CC Addresses
                    if (strCC != string.Empty)
                    {
                        foreach (string sCC in strCC.Split(";".ToCharArray()))
                        {
                            mailMessage.CC.Add(sCC);
                        }
                    }
                    int    attachementCount = 0;
                    double totalSizeInMB    = 0;
                    var    attachmentsOrderedByImportance = emailAttachments.OrderByDescending(issue => issue.importance);

                    foreach (EmailAttachment attachment in attachmentsOrderedByImportance)
                    {
                        string fileName = Path.Combine(emailMessageBody.attachmentFolder, attachment.name);
                        if (File.Exists(fileName))
                        {
                            //Apply maximum size restriction rule
                            FileInfo f        = new FileInfo(fileName);
                            long     filesize = f.Length;
                            double   sizeInMB = (filesize / 1024f) / 1024f;

                            if ((totalSizeInMB + sizeInMB) >= emailMessageBody.maxAttachmentsSizeInMb)
                            {
                                LoggingHelper.Warn(string.Format("The size of the attachment is above the configured limit. Alarm {0}. FileName :{1}. Configured Value :{2}. Current Limit: {3}", alarm.Name, attachment.name, emailMessageBody.maxAttachmentsSizeInMb, totalSizeInMB));
                            }
                            else if (attachementCount >= emailMessageBody.maxAttachments)  //Apply Maximum attachments/email rule
                            {
                                LoggingHelper.Warn(string.Format("Maximum attachments count reached for alarm {0}. Configured Value :{1}. Current Limit: {2}", alarm.Name, emailMessageBody.maxAttachments, attachementCount));
                            }
                            else
                            {
                                mailMessage.Attachments.Add(new Attachment(fileName));
                                totalSizeInMB += sizeInMB; // Attachment Size
                                attachementCount++;        // Attachement Count
                            }
                        }
                        else
                        {
                            LoggingHelper.Warn(string.Format(" Attachment file {0} cannot be found.", attachment));
                        }
                    }


                    MailPriority mailPriority = MailPriority.Normal;
                    switch (alarm.EmailPriority)
                    {
                    case "1":
                        mailPriority = MailPriority.High;
                        break;

                    case "0":
                        mailPriority = MailPriority.Low;
                        break;
                    }
                    mailMessage.Priority = mailPriority;
                    smtp.Send(mailMessage);
                    LoggingHelper.Info("SMTP Notification channel posted the message successfully");
                    return(true);
                }
                catch (Exception ex)
                {
                    LoggingHelper.Error("SMTP Notification channel failed. Error " + ex.Message);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Error("SMTP Notification channel failed. Error " + ex.Message);
                return(false);
            }
        }