public static void Email(this Contact contact, EmailTypeEnum type, string value)
        {
            if (String.IsNullOrEmpty(value))
            {
                return;
            }

            contact.ChangeValueDelegate += delegate(Contact x) {
                x.Fields = x.Fields ?? new List <Field>();
                if (!x.Fields.Any(fl => fl.Id == (int)ContactFieldsEnum.Email))
                {
                    x.Fields.Add(new Field {
                        Id = (int)ContactFieldsEnum.Email, Values = new List <FieldValue>()
                    });
                }

                var current = x.Email();
                if (current != null && current.Any(p => p.Key == type))
                {
                    x.Fields.FirstOrDefault(fl => fl.Id == (int)ContactFieldsEnum.Email).Values.FirstOrDefault(p => p.Enum == (int)type).Value = value.ClearEmail();
                }
                else
                {
                    x.Fields.FirstOrDefault(fl => fl.Id == (int)ContactFieldsEnum.Email).Values.Add(new FieldValue {
                        Enum = (int)type, Value = value.ClearEmail()
                    });
                }
            };
        }
示例#2
0
        private string GetEmailTemplateFromEmailType(EmailTypeEnum emailViewEmailType)
        {
            string result;

            switch (emailViewEmailType)
            {
            case EmailTypeEnum.Order:
                result = "order.html";
                break;

            case EmailTypeEnum.CreateBooking:
                result = "createBooking.html";
                break;

            case EmailTypeEnum.InvitedGuest:
                result = "createInvitationGuest.html";
                break;

            case EmailTypeEnum.InvitedHost:
                result = "createInvitationHost.html";
                break;

            default:
                result = "order.html";
                break;
            }

            return(result);
        }
示例#3
0
 public virtual void AddEmail(string value, EmailTypeEnum type = EmailTypeEnum.PRIV)
 {
     if (String.IsNullOrEmpty(value) || CheckEmailDouble(value))
     {
         return;
     }
     SetField((int)ContactSystemFields.Email, value, (int)type, add: true);
 }
示例#4
0
        public string SendEmail(EmailTypeEnum emailType, string emailAddress)
        {
            switch (emailType)
            {
            case EmailTypeEnum.AccountCreationConfirmationEmail:
                return(this.AccountConfirmationEmail(emailAddress));

            default: return(null);
            }
        }
示例#5
0
        public void EmailExtraB_Every_Property_Has_Get_Set_Test()
        {
            string val1 = "Some text";

            emailExtraB.EmailReportTest = val1;
            Assert.AreEqual(val1, emailExtraB.EmailReportTest);
            string val2 = "Some text";

            emailExtraB.EmailText = val2;
            Assert.AreEqual(val2, emailExtraB.EmailText);
            string val3 = "Some text";

            emailExtraB.LastUpdateContactText = val3;
            Assert.AreEqual(val3, emailExtraB.LastUpdateContactText);
            string val4 = "Some text";

            emailExtraB.EmailTypeText = val4;
            Assert.AreEqual(val4, emailExtraB.EmailTypeText);
            int val5 = 45;

            emailExtraB.EmailID = val5;
            Assert.AreEqual(val5, emailExtraB.EmailID);
            int val6 = 45;

            emailExtraB.EmailTVItemID = val6;
            Assert.AreEqual(val6, emailExtraB.EmailTVItemID);
            string val7 = "Some text";

            emailExtraB.EmailAddress = val7;
            Assert.AreEqual(val7, emailExtraB.EmailAddress);
            EmailTypeEnum val8 = (EmailTypeEnum)3;

            emailExtraB.EmailType = val8;
            Assert.AreEqual(val8, emailExtraB.EmailType);
            DateTime val9 = new DateTime(2010, 3, 4);

            emailExtraB.LastUpdateDate_UTC = val9;
            Assert.AreEqual(val9, emailExtraB.LastUpdateDate_UTC);
            int val10 = 45;

            emailExtraB.LastUpdateContactTVItemID = val10;
            Assert.AreEqual(val10, emailExtraB.LastUpdateContactTVItemID);
            bool val11 = true;

            emailExtraB.HasErrors = val11;
            Assert.AreEqual(val11, emailExtraB.HasErrors);
            IEnumerable <ValidationResult> val36 = new List <ValidationResult>()
            {
                new ValidationResult("First CSSPError Message")
            }.AsEnumerable();

            emailExtraB.ValidationResults = val36;
            Assert.AreEqual(val36, emailExtraB.ValidationResults);
        }
示例#6
0
        protected void SetTemplate(EmailTypeEnum type)
        {
            var body = _repository.GetOne <EmailTemplate>(x => x.Language.Equals(Language) && x.EmailType.Equals(type));

            Subject    = body.Subject;
            FromAdress = new MailboxAddress(
                "Building-admin.com",
                body.Address
                );
            Template = body.Template;
        }
示例#7
0
        public void Email_Every_Property_Has_Get_Set_Test()
        {
            int val1 = 45;

            email.EmailID = val1;
            Assert.AreEqual(val1, email.EmailID);
            int val2 = 45;

            email.EmailTVItemID = val2;
            Assert.AreEqual(val2, email.EmailTVItemID);
            string val3 = "Some text";

            email.EmailAddress = val3;
            Assert.AreEqual(val3, email.EmailAddress);
            EmailTypeEnum val4 = (EmailTypeEnum)3;

            email.EmailType = val4;
            Assert.AreEqual(val4, email.EmailType);
            DateTime val5 = new DateTime(2010, 3, 4);

            email.LastUpdateDate_UTC = val5;
            Assert.AreEqual(val5, email.LastUpdateDate_UTC);
            int val6 = 45;

            email.LastUpdateContactTVItemID = val6;
            Assert.AreEqual(val6, email.LastUpdateContactTVItemID);
            bool val7 = true;

            email.HasErrors = val7;
            Assert.AreEqual(val7, email.HasErrors);
            IEnumerable <ValidationResult> val24 = new List <ValidationResult>()
            {
                new ValidationResult("First CSSPError Message")
            }.AsEnumerable();

            email.ValidationResults = val24;
            Assert.AreEqual(val24, email.ValidationResults);
        }
示例#8
0
        public void Generate(EmailTypeEnum emailType, object model)
        {
            var templateFile = GetEmailTemplateFile(emailType);
            var file = new FileInfo(templateFile);
            if (!file.Exists)
            {
                throw new FileNotFoundException(string.Format("Template file {0} not found", templateFile));
            }

            try
            {
                var templateContent = File.ReadAllText(file.FullName);
                int themeStart = templateContent.IndexOf(THEME_BEGIN_STRING);
                int themeEnd = templateContent.IndexOf(THEME_END_STRING, themeStart + THEME_BEGIN_STRING.Length);
                int length = themeEnd - (themeStart + THEME_BEGIN_STRING.Length);
                Title = templateContent.Substring(themeStart + THEME_BEGIN_STRING.Length, length);
                Body = RazorEngine.Razor.Parse(templateContent, model);
            }
            catch (Exception e)
            {
                throw new Exception("Razor generation exception", e);
            }
        }
示例#9
0
文件: Email.cs 项目: Organus/LRS_SORT
        public static bool SendEmail(SortMainObject sort, EmailTypeEnum emailType, bool includeAuthors, ref string errorMsg)
        {
            try
            {
                var template = EmailTemplateObject.GetEmailTemplate(emailType.ToString());
                if (template != null)
                {
                    string subject = template.Header.Replace("{STI_Number}", sort.TitleStr).Replace("{PublishTitle}", sort.PublishTitle);
                    string body    = template.Body
                                     .Replace("{STI_Number}", sort.TitleStr)
                                     .Replace("{PublishTitle}", sort.PublishTitle)
                                     .Replace("{Authors}", string.Join(", ", sort.Authors.Select(n => $"{n.FirstName} {n.LastName}")))
                                     .Replace("{DueDate}", $"{sort.DueDate:d}")
                                     .Replace("{ReviewStatus}", sort.ReviewStatus)
                                     .Replace("{ReviewProgress}", $"{sort.ReviewProgress:P}")
                                     .Replace("{ViewUrl}", $"<a href=\"{Config.SortUrl(false).TrailingForwardSlash()}Artifact/{sort.SortMainId}\">STI Artifact</a>")
                                     .Replace("{EditUrl}", $"<a href=\"{Config.SortUrl(false).TrailingForwardSlash()}Artifact/Edit/{sort.SortMainId}\">STI Artifact</a>");

                    if (emailType == EmailTypeEnum.FirstYearReminder || emailType == EmailTypeEnum.DelayedReminder)
                    {
                        return(SendReleaseOfficerEmail(sort, subject, body, emailType, ref errorMsg));
                    }

                    return(SendOwnerEmail(sort, subject, body, includeAuthors, emailType, ref errorMsg));
                }

                errorMsg = $"Unable to find the Template for Email Type: {emailType}";
            }
            catch (Exception ex)
            {
                ErrorLogObject.LogError("Email::SendEmail", ex);
                errorMsg = $"Exception Caught while attempting to send an email: {ex.Message}";
            }

            return(false);
        }
示例#10
0
文件: Email.cs 项目: Organus/LRS_SORT
        public static bool SendEmail(MainObject main, ReviewObject review, EmailTypeEnum emailType, string comment, ref string errorMsg)
        {
            try
            {
                var template = EmailTemplateObject.GetEmailTemplate(emailType);
                if (template != null)
                {
                    string subject = template.Header.Replace("{STI_Number}", main.StiNumber ?? string.Empty).Replace("{Title}", main.Title ?? string.Empty);
                    string body    = ConstructBody(main, review, comment, template);
                    switch (emailType)
                    {
                    case EmailTypeEnum.ReleaseOfficerComplete:
                        return(SendReleaseOfficerEmail(subject, body, ref errorMsg));

                    case EmailTypeEnum.ClassReviewer:
                    case EmailTypeEnum.ExportReviewer:
                    case EmailTypeEnum.ManagerReviewer:
                    case EmailTypeEnum.PeerReviewer:
                    case EmailTypeEnum.TechReviewer:
                    case EmailTypeEnum.ReviewReminder:
                        return(review != null?SendReviewerEmail(review, subject, body, ref errorMsg) : SendReviewersEmail(main, subject, body, emailType, ref errorMsg));

                    default:
                        return(SendOwnerEmail(main, subject, body, template.IncludeAuthors, template.IncludeContacts, ref errorMsg));
                    }
                }

                errorMsg = $"Unable to find the Template for Email Type: {emailType}";
            }
            catch (Exception ex)
            {
                errorMsg = $"Exception Caught while attempting to send an email: {ex.Message}";
            }

            return(false);
        }
示例#11
0
 public EmailData(string token, string email, EmailTypeEnum type)
 {
     Token = token;
     Email = email;
     Type  = type;
 }
示例#12
0
        // Post
        public EmailModel PostAddOrModifyDB(FormCollection fc)
        {
            ContactOK contactOK = IsContactOK();

            if (!string.IsNullOrWhiteSpace(contactOK.Error))
            {
                return(ReturnError(contactOK.Error));
            }

            int           ContactTVItemID = 0;
            int           EmailTVItemID   = 0;
            string        EmailAddress    = "";
            int           EmailTypeInt    = 0;
            EmailTypeEnum EmailType       = EmailTypeEnum.Error;

            int.TryParse(fc["ContactTVItemID"], out ContactTVItemID);
            if (ContactTVItemID == 0)
            {
                return(ReturnError(string.Format(ServiceRes._IsRequired, ServiceRes.ContactTVItemID)));
            }

            int.TryParse(fc["EmailTVItemID"], out EmailTVItemID);
            // if 0 then want to add new TVItem else want to modify

            EmailAddress = fc["EmailAddress"];
            if (string.IsNullOrWhiteSpace(EmailAddress))
            {
                return(ReturnError(string.Format(ServiceRes._IsRequired, ServiceRes.EmailAddress)));
            }

            int.TryParse(fc["EmailType"], out EmailTypeInt);
            if (EmailTypeInt == 0)
            {
                return(ReturnError(string.Format(ServiceRes._IsRequired, ServiceRes.EmailType)));
            }

            EmailType = (EmailTypeEnum)EmailTypeInt;

            EmailModel EmailModel = new EmailModel();

            using (TransactionScope ts = new TransactionScope())
            {
                if (EmailTVItemID == 0)
                {
                    TVItemModel tvItemModelRoot = _TVItemService.GetRootTVItemModelDB();
                    if (!string.IsNullOrWhiteSpace(tvItemModelRoot.Error))
                    {
                        return(ReturnError(tvItemModelRoot.Error));
                    }

                    TVItemModel tvItemModelContact = _TVItemService.GetTVItemModelWithTVItemIDDB(ContactTVItemID);
                    if (!string.IsNullOrWhiteSpace(tvItemModelContact.Error))
                    {
                        return(ReturnError(tvItemModelContact.Error));
                    }

                    EmailModel EmailModelNew = new EmailModel()
                    {
                        EmailAddress = EmailAddress,
                        EmailType    = EmailType,
                    };

                    string TVText = CreateTVText(EmailModelNew);
                    if (string.IsNullOrWhiteSpace(TVText))
                    {
                        return(ReturnError(string.Format(ServiceRes._IsRequired, ServiceRes.TVText)));
                    }

                    TVItemModel tvItemModelEmail = _TVItemService.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelRoot.TVItemID, TVText, TVTypeEnum.Email);
                    if (!string.IsNullOrWhiteSpace(tvItemModelEmail.Error))
                    {
                        // Should add
                        tvItemModelEmail = _TVItemService.PostAddChildTVItemDB(tvItemModelRoot.TVItemID, TVText, TVTypeEnum.Email);
                        if (!string.IsNullOrWhiteSpace(tvItemModelEmail.Error))
                        {
                            return(ReturnError(tvItemModelEmail.Error));
                        }

                        EmailModelNew.EmailTVItemID = tvItemModelEmail.TVItemID;

                        EmailModel = PostAddEmailDB(EmailModelNew);
                        if (!string.IsNullOrWhiteSpace(EmailModel.Error))
                        {
                            return(ReturnError(EmailModel.Error));
                        }
                    }

                    EmailModel = GetEmailModelWithEmailTVItemIDDB(tvItemModelEmail.TVItemID);
                    if (!string.IsNullOrWhiteSpace(EmailModel.Error))
                    {
                        return(ReturnError(EmailModel.Error));
                    }

                    TVItemLinkModel tvItemLinkModelNew = new TVItemLinkModel()
                    {
                        DBCommand           = DBCommandEnum.Original,
                        FromTVItemID        = tvItemModelContact.TVItemID,
                        ToTVItemID          = tvItemModelEmail.TVItemID,
                        FromTVType          = tvItemModelContact.TVType,
                        ToTVType            = TVTypeEnum.Email,
                        StartDateTime_Local = DateTime.Now,
                        Ordinal             = 0,
                        TVLevel             = 0,
                        TVPath = "p" + tvItemModelContact.TVItemID + "p" + tvItemModelEmail.TVItemID,
                    };

                    TVItemLinkModel tvItemLinkModel = _TVItemLinkService.GetTVItemLinkModelWithFromTVItemIDAndToTVItemIDDB(tvItemModelContact.TVItemID, tvItemModelEmail.TVItemID);
                    if (!string.IsNullOrWhiteSpace(tvItemLinkModel.Error))
                    {
                        tvItemLinkModel = _TVItemLinkService.PostAddTVItemLinkDB(tvItemLinkModelNew);
                        if (!string.IsNullOrWhiteSpace(tvItemLinkModel.Error))
                        {
                            return(ReturnError(tvItemLinkModel.Error));
                        }
                    }
                }
                else
                {
                    EmailModel EmailModelToChange = GetEmailModelWithEmailTVItemIDDB(EmailTVItemID);
                    if (!string.IsNullOrWhiteSpace(EmailModelToChange.Error))
                    {
                        return(ReturnError(EmailModelToChange.Error));
                    }

                    EmailModelToChange.EmailAddress = EmailAddress;
                    EmailModelToChange.EmailType    = EmailType;

                    EmailModel = PostUpdateEmailDB(EmailModelToChange);
                    if (!string.IsNullOrWhiteSpace(EmailModel.Error))
                    {
                        return(ReturnError(EmailModel.Error));
                    }

                    foreach (LanguageEnum Lang in LanguageListAllowable)
                    {
                        TVItemLanguageModel tvItemLanguageModel = _TVItemService._TVItemLanguageService.GetTVItemLanguageModelWithTVItemIDAndLanguageDB(EmailModelToChange.EmailTVItemID, Lang);
                        if (!string.IsNullOrWhiteSpace(tvItemLanguageModel.Error))
                        {
                            return(ReturnError(tvItemLanguageModel.Error));
                        }

                        tvItemLanguageModel.TVText = CreateTVText(EmailModelToChange);

                        tvItemLanguageModel = _TVItemService._TVItemLanguageService.PostUpdateTVItemLanguageDB(tvItemLanguageModel);
                        if (!string.IsNullOrWhiteSpace(tvItemLanguageModel.Error))
                        {
                            return(ReturnError(tvItemLanguageModel.Error));
                        }
                    }
                }

                ts.Complete();
            }

            return(EmailModel);
        }
示例#13
0
文件: Email.cs 项目: Organus/LRS_SORT
        private static bool SendOwnerEmail(SortMainObject sort, string subject, string body, bool includeAuthors, EmailTypeEnum emailType, ref string errorMsg)
        {
            bool   allMailSent = false;
            string ownerEmail  = ConfigurationManager.AppSettings["OwnerEmail"].ToString();

            try
            {
                Email  email   = new Email();
                string addInfo = string.Empty;
                email.SendTo  = new List <string>();
                email.Subject = subject;


                foreach (var contact in sort.Contacts)
                {
                    if (!string.IsNullOrWhiteSpace(contact.EmployeeId))
                    {
                        var user = UserObject.GetUser(contact.EmployeeId);
                        if (user != null && !string.IsNullOrWhiteSpace(user.Email))
                        {
                            if (!email.SendTo.Exists(n => n.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)))
                            {
                                email.SendTo.Add(user.Email);
                            }
                        }
                    }
                }

                if (email.SendTo.Count == 0)
                {
                    if (!string.IsNullOrWhiteSpace(sort.OwnerEmail))
                    {
                        if (!email.SendTo.Exists(n => n.Equals(sort.OwnerEmail, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            email.SendTo.Add(sort.OwnerEmail);
                        }
                    }
                }

                if (includeAuthors)
                {
                    foreach (var author in sort.Authors.Where(n => n.AffiliationEnum == AffiliationEnum.INL))
                    {
                        if (!string.IsNullOrWhiteSpace(author.EmployeeId))
                        {
                            var user = UserObject.GetUser(author.EmployeeId);
                            if (user != null && !string.IsNullOrWhiteSpace(user.Email))
                            {
                                email.SendTo.Add(user.Email);
                            }
                        }
                    }
                }

                if (email.SendTo.Count == 0)
                {
                    email.SendTo.Add(ownerEmail);
                    addInfo = "<em><p><strong>This message has been sent to you in lieu of the intended target.  Their email was not found in Employee Data. Please review the email and determine appropriate course of action.</strong></p></em><hr />";
                }

                email.Body  = addInfo + body;
                email.Body += "<hr /><p> You are being contacted because you are either the Owner or a Contact for the Artifact.</p>";
                email.Body += "<p> If you believe this has been in error, please contact the admin: " + ownerEmail + "</p>";
                email.Send(emailType);

                allMailSent = true;
            }
            catch (Exception ex)
            {
                ErrorLogObject.LogError("Email::SendOwnerEmail", ex);
                errorMsg = $"Exeption Caught on sending Email: {ex.Message}";
            }
            return(allMailSent);
        }
示例#14
0
        // *********************************************************************
        //  SendEmail
        //
        /// <summary>
        /// This method sends an email to the user Username - the email template is identified by
        /// the EmailID parameter.
        /// </summary>
        /// <param name="Username">The user to send the email to.</param>
        /// <param name="EmailType">The specific email template.</param>
        /// <param name="PostID">Information on a particular post.</param>
        /// <param name="Bcc">A comma-separated list of email addresses to add to the Bcc property.
        /// This is used when there are numerous recipients for a particular email, such as the thread
        /// tracking email template.</param>
        /// <returns>A boolean, indicating whether or not the email was sent successfully.</returns>
        /// <remarks>When sending a deleted email messages, the strBcc parameter holds the
        /// *reason* why the message was deleted.</remarks>
        ///
        // ********************************************************************/
        public static bool SendEmail(String username, EmailTypeEnum emailType, int postID, string bcc, string deleteReason)
        {
            // if we don't wish to send emails at all, bail out now
            if (!Globals.SendEmail)
            {
                return(false);
            }

            // both the username and bcc field can't be empty
            if (username.Length == 0 && bcc.Length == 0)
            {
                return(false);
            }

            if (bcc == null)
            {
                bcc = "";
            }

            // if we were passed in a username, get the username info
            String strEmail = "";
            User   user     = null;
            int    dbTimezoneOffset;
            int    iTimezoneOffset = Globals.DBTimezone;

            dbTimezoneOffset = iTimezoneOffset;

            if (username.Length > 0)
            {
                user            = Users.GetUserInfo(username, false);
                strEmail        = user.Email;
                iTimezoneOffset = user.Timezone;
            }

            // read in the email
            EmailTemplate email = GetEmailTemplateInfo((int)emailType);

            // Constrcut the email
            MailMessage msg = new MailMessage();

            if (bcc.Length > 0 && emailType != EmailTypeEnum.MessageDeleted)
            {
                msg.Bcc = bcc;
            }
            else
            {
                msg.To = strEmail;              // assumes strEmail was set
            }

            msg.From            = email.From;
            msg.Subject         = FormatEmail(email.Subject, user, postID, iTimezoneOffset, dbTimezoneOffset, null);
            msg.Priority        = email.Priority;
            msg.Body            = FormatEmail(email.Body, user, postID, iTimezoneOffset, dbTimezoneOffset, deleteReason) + "\n";
            SmtpMail.SmtpServer = Globals.SmtpServer;

            try {
                SmtpMail.Send(msg);
            } catch (Exception) {
                return(false);
            }

            return(true);
        }
示例#15
0
 // *********************************************************************
 //  SendEmail
 //
 /// <summary>
 /// Sends a particular email to a particular user based on the contents of a particular post.
 /// </summary>
 /// <param name="Username">The user to send the email to.</param>
 /// <param name="EmailType">The type of email to send.</param>
 /// <param name="PostID">The particular post to base the email on.</param>
 /// <returns>
 /// A boolean, indicating whether or not the email was sent successfully.
 /// </returns>
 ///
 // ********************************************************************/
 public static bool SendEmail(String username, EmailTypeEnum emailType, int postID, string bcc)
 {
     return(SendEmail(username, emailType, postID, bcc, null));
 }
示例#16
0
文件: Email.cs 项目: Organus/LRS_SORT
        public static bool SendEmail(MainObject main, ReviewObject review, EmailTypeEnum emailType, string comment)
        {
            string errorMsg = string.Empty;

            return(SendEmail(main, review, emailType, comment, ref errorMsg));
        }
示例#17
0
    /// <summary>
    /// 邮件发送
    /// </summary>
    /// <param name="emailType">邮件类型</param>
    /// <param name="emailTo">收件人的电子邮件地址。使用分号 (;) 分隔多名收件人。</param>
    /// <param name="emailTitle">电子邮件的主题行。</param>
    /// <param name="emailContent">电子邮件的正文。如果 isBodyHtml 为 true,则将正文中的 HTML 解释为标记。</param>
    /// <param name="filePath">(可选)文件名的集合,用于指定要附加到电子邮件中的文件;如果没有要附加的文件,则为 null。默认值为 null。</param>
    /// <param name="additionalHeaders">(可选)标头的集合,可添加到此电子邮件包含的正常 SMTP 标头中;如果不发送其他标头,则为 null。默认值为 null。</param>
    /// <param name="CC">邮件抄送人</param>
    public static bool SendMail(EmailTypeEnum emailType, string emailTo, string emailTitle,
                                string emailContent, IEnumerable <string> filePath = null, IEnumerable <string> additionalHeaders = null, string CC = "")
    {
        if (string.IsNullOrEmpty(emailTitle))
        {
            ErrorLog("暂无标题", "标题不能为空");
            return(false);
        }
        if (string.IsNullOrEmpty(emailContent))
        {
            ErrorLog(emailTitle, "邮件内容不能为空");
            return(false);
        }
        var config = EmailConfigs.FirstOrDefault(s => s.ConfigName == emailType.ToString());

        if (config == null)
        {
            ErrorLog(emailTitle, "无法获取有效的邮件配置信息");
            return(false);
        }

        var smtp = new SmtpClient
        {
            UseDefaultCredentials = true,
            Credentials           = new NetworkCredential(config.UserName, config.Password),
            DeliveryMethod        = SmtpDeliveryMethod.Network,
            Port      = config.Port,
            Host      = config.Host,
            EnableSsl = true
        };

        var mail = new MailMessage {
            From = new MailAddress(config.From)
        };

        if (!string.IsNullOrEmpty(emailTo))
        {
            emailTo = emailTo.Replace(";", ";").Trim(';');
            foreach (var mailTo in emailTo.Split(';'))
            {
                if (RegEmail(mailTo))
                {
                    mail.To.Add(new MailAddress(mailTo));
                }
            }
        }

        if (!string.IsNullOrEmpty(CC))
        {
            CC = CC.Replace(";", ";").Trim(';');
            foreach (var item in CC.Split(';'))
            {
                if (RegEmail(item))
                {
                    mail.CC.Add(new MailAddress(item));
                }
            }
        }
        if (mail.To.Count == 0 && mail.CC.Count == 0)
        {
            ErrorLog(emailTitle, "收件人和抄送人不能同时为空");
            return(false);
        }
        mail.Subject    = emailTitle;
        mail.Body       = emailContent;
        mail.IsBodyHtml = true;
        if (filePath != null)
        {
            foreach (var item in filePath)
            {
                if (Directory.Exists(item))
                {
                    mail.Attachments.Add(new Attachment(item));
                }
            }
        }

        if (additionalHeaders != null)
        {
            foreach (var item in additionalHeaders)
            {
                try
                {
                    mail.Headers.Add(null, item);
                }
                catch (Exception ex)
                {
                }
            }
        }

        try
        {
            smtp.Send(mail);
        }
        catch (Exception ex)
        {
            ErrorLog(emailTitle, ex.Message);
            return(false);
        }
        #region 发送邮件日志
        Log(emailTo, emailTitle, CC, config);
        #endregion
        return(true);
    }
示例#18
0
 /// <summary>
 /// Create an instance of IEmail.
 /// </summary>
 /// <param name="emailType">Email type.</param>
 /// <returns>The implementation of IEmail.</returns>
 public IEmail Create(EmailTypeEnum emailType) => _factories[emailType];
示例#19
0
文件: Email.cs 项目: Organus/LRS_SORT
        private void Send(EmailTypeEnum emailType)
        {
            MailMessage message = new MailMessage();

            message.From       = new MailAddress(Config.FromAddress);
            message.Subject    = Subject;
            message.Body       = Body;
            message.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["EmailServer"]);

            if (Config.ApplicationMode == ApplicationMode.Production)// || (Config.ApplicationMode == ApplicationMode.Acceptance && emailType == EmailTypeEnum.Initial))
            {
                // We are in prodution, send the email to the person(s) we should.
                foreach (string to in SendTo)
                {
                    message.To.Clear();
                    message.CC.Clear();
                    message.Bcc.Clear();
                    message.To.Add(new MailAddress(to));
                    if (!String.IsNullOrEmpty(CC))
                    {
                        message.CC.Add(new MailAddress(CC));
                    }
                    smtp.Send(message);
                }
            }
            else if (Config.ApplicationMode != ApplicationMode.CyberScan)
            {
                // As long as we are not in production or CyberScan, send email to user
                // or if user does not have email, send to developer or acceptance person.
                message.Subject = "**TESTING** " + message.Subject;
                message.Body    = "<em>Original Email Recipient(s): " + string.Join(", ", SendTo) + "</em><hr />" + Body;
                message.To.Clear();
                message.CC.Clear();
                message.Bcc.Clear();
                try
                {
                    if (!string.IsNullOrWhiteSpace(UserObject.RealCurrentUser.Email))
                    {
                        message.To.Add(UserObject.RealCurrentUser.Email);
                    }
                }
                catch (Exception ex)
                {
                    ErrorLogObject.LogError("Email::Send", ex);
                }

                if (message.To.Count == 0)
                {
                    if (Config.ApplicationMode == ApplicationMode.Acceptance)
                    {
                        message.To.Add(Config.OwnerEmail);
                    }
                    else
                    {
                        message.To.Add(Config.DeveloperEmail);
                    }
                }
                smtp.Send(message);
            }
        }
示例#20
0
 public EmailTemplateObject GetEmailTemplate(EmailTypeEnum emailType) => Config.Conn.QueryFirstOrDefault <EmailTemplateObject>("SELECT * FROM dat_EmailTemplate WHERE EmailType = @EmailType", new { EmailType = emailType.ToString() });
示例#21
0
 public static string GetEmailTemplateFile(EmailTypeEnum type)
 {
     return Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin\\EmailTemplates\\", type.ToString() + ".cshtml");
 }
示例#22
0
        public void SendInternal(Guid accountId, EmailTypeEnum emailType, Object model)
        {
            var account = AccountsRepository.Find(x => x.ExternalId == accountId);
            var sender = EmailTypeRepository.Find(x => x.EmailTypeId == (int)emailType).Sender;
            Generator.Generate(emailType, model);
            var smtp = GetSmtpClient(sender);

            using (var message = new MailMessage(sender.Email, sender.Email)
            {
                Subject = Generator.Title,
                Body = Generator.Body,
                IsBodyHtml = true
            })
            {
                smtp.Send(message);
            }

            EmailRepository.SaveOrUpdateAll(new Data.Entities.Email() { AccountId = account.ExternalId, EmailContent = Generator.Body, EmailTitle = emailType });
        }
示例#23
0
文件: Email.cs 项目: Organus/LRS_SORT
        public static bool SendEmail(SortMainObject sort, EmailTypeEnum emailType, bool includeAuthors = false)
        {
            string errorMsg = string.Empty;

            return(SendEmail(sort, emailType, includeAuthors, ref errorMsg));
        }
示例#24
0
 // *********************************************************************
 //  SendEmail
 //
 /// <summary>
 /// Sends a particular email type to a particular user.
 /// </summary>
 /// <param name="username">The user to send the email to.</param>
 /// <param name="emailType">The type of email to send.</param>
 /// <returns>A boolean, indicating whether or not the email was sent successfully.</returns>
 ///
 // ********************************************************************/
 public static bool SendEmail(String username, EmailTypeEnum emailType)
 {
     return(SendEmail(username, emailType, 0, null, null));
 }
示例#25
0
 /// <summary>
 /// Create an instance of IEmail.
 /// </summary>
 /// <param name="emailType">Email type.</param>
 /// <returns>The implementation of IEmail.</returns>
 public EmailAbstract Create(EmailTypeEnum emailType) => _factories[emailType];
示例#26
0
文件: Email.cs 项目: Organus/LRS_SORT
        private static bool SendReviewersEmail(MainObject main, string subject, string body, EmailTypeEnum emailType, ref string errorMsg)
        {
            bool          allMailSent    = false;
            List <string> recipientNames = new List <string>();

            try
            {
                Email  email   = new Email();
                string addInfo = string.Empty;
                email.SendTo  = new List <string>();
                email.Subject = subject;
                switch (emailType)
                {
                case EmailTypeEnum.ClassReviewer:
                    foreach (var reviewer in MemoryCache.GetGenericReviewData(ReviewerTypeEnum.Classification) ?? new List <GenericReviewDataObject>())
                    {
                        if (reviewer != null && !string.IsNullOrWhiteSpace(reviewer.GenericEmail))
                        {
                            email.SendTo.Add(reviewer.GenericEmail);
                        }
                    }

                    foreach (var r in main.Reviewers.Where(n => n.ReviewerTypeEnum == ReviewerTypeEnum.Classification))
                    {
                        r.LastEmailDate = DateTime.Now;
                        r.Save();
                    }

                    recipientNames.Add("Classification Reviewer");
                    break;

                case EmailTypeEnum.ExportReviewer:
                    foreach (var reviewer in MemoryCache.GetGenericReviewData(ReviewerTypeEnum.ExportControl) ?? new List <GenericReviewDataObject>())
                    {
                        if (reviewer != null && !string.IsNullOrWhiteSpace(reviewer.GenericEmail))
                        {
                            email.SendTo.Add(reviewer.GenericEmail);
                        }
                    }

                    foreach (var r in main.Reviewers.Where(n => n.ReviewerTypeEnum == ReviewerTypeEnum.Classification))
                    {
                        r.LastEmailDate = DateTime.Now;
                        r.Save();
                    }

                    recipientNames.Add("Export Compliance Reviewer");
                    break;

                case EmailTypeEnum.TechReviewer:
                    foreach (var reviewer in MemoryCache.GetGenericReviewData(ReviewerTypeEnum.TechDeployment) ?? new List <GenericReviewDataObject>())
                    {
                        if (reviewer != null && !string.IsNullOrWhiteSpace(reviewer.GenericEmail))
                        {
                            email.SendTo.Add(reviewer.GenericEmail);
                        }
                    }

                    foreach (var r in main.Reviewers.Where(n => n.ReviewerTypeEnum == ReviewerTypeEnum.TechDeployment))
                    {
                        r.LastEmailDate = DateTime.Now;
                        r.Save();
                    }

                    recipientNames.Add("Technical Deployment Reviewer");
                    break;

                case EmailTypeEnum.ManagerReviewer:
                    foreach (var reviewer in main.Reviewers.Where(n => n.ReviewerTypeEnum == ReviewerTypeEnum.Manager))
                    {
                        if (reviewer != null && !string.IsNullOrWhiteSpace(reviewer.Email))
                        {
                            email.SendTo.Add(reviewer.Email);
                            recipientNames.Add(reviewer.ReviewerName);
                            reviewer.LastEmailDate = DateTime.Now;
                            reviewer.Save();
                        }
                    }

                    break;

                case EmailTypeEnum.PeerReviewer:
                    foreach (var reviewer in main.Reviewers.Where(n => n.ReviewerTypeEnum == ReviewerTypeEnum.PeerTechnical))
                    {
                        if (reviewer != null && !string.IsNullOrWhiteSpace(reviewer.Email))
                        {
                            email.SendTo.Add(reviewer.Email);
                            recipientNames.Add(reviewer.ReviewerName);
                            reviewer.LastEmailDate = DateTime.Now;
                            reviewer.Save();
                        }
                    }

                    break;

                default:
                    return(false);
                }

                if (email.SendTo.Count == 0)
                {
                    return(false);
                }

                email.Body = addInfo + body.Replace("{RecipientsName}", string.Join(" : ", recipientNames));
                AddContactInfo(ref email);
                email.Send();

                allMailSent = true;
            }
            catch (Exception ex)
            {
                errorMsg = $"Exeption Caught on sending Email: {ex.Message}";
            }
            return(allMailSent);
        }
示例#27
0
 public static EmailTemplateObject GetEmailTemplate(EmailTypeEnum emailType) => repo.GetEmailTemplate(emailType);
示例#28
0
文件: Email.cs 项目: Organus/LRS_SORT
        private static bool SendReleaseOfficerEmail(SortMainObject sort, string subject, string body, EmailTypeEnum emailType, ref string errorMsg)
        {
            bool   allMailSent = false;
            string ownerEmail  = ConfigurationManager.AppSettings["OwnerEmail"].ToString();

            try
            {
                Email  email   = new Email();
                string addInfo = string.Empty;
                email.SendTo  = new List <string>();
                email.Subject = subject;

                foreach (var user in UserObject.GetUsers().Where(n => n.IsInAnyRole("ReleaseOfficial")))
                {
                    if (!string.IsNullOrWhiteSpace(user.Email))
                    {
                        email.SendTo.Add(user.Email);
                    }
                }

                if (email.SendTo.Count == 0)
                {
                    email.SendTo.Add(ownerEmail);
                    addInfo = "<em><p><strong>This message has been sent to you in lieu of the intended target.  Their email was not found in Employee Data. Please review the email and determine appropriate course of action.</strong></p></em><hr />";
                }

                email.Body  = addInfo + body;
                email.Body += "<hr /><p> You are being contacted because you are a Release Official in the SORT system.</p>";
                email.Body += "<p> If you believe this has been in error, please contact the admin: " + ownerEmail + "</p>";
                email.Send(emailType);

                allMailSent = true;
            }
            catch (Exception ex)
            {
                ErrorLogObject.LogError("Email::SendReleaseOfficerEmail", ex);
                errorMsg = $"Exeption Caught on sending Email: {ex.Message}";
            }
            return(allMailSent);
        }