Exemplo n.º 1
0
 /// <summary>
 /// Constructeur du formulaire
 /// </summary>
 /// <param name="infoEcole"></param>
 /// <param name="mailType"></param>
 /// <param name="_applClass"></param>
 public frmSendMail(Ecole infoEcole, MailType mailType, ApplClass _applClass)
 {
     InitializeComponent();
     _infoEcole = infoEcole;
     _mailType = mailType;
     p_applClass = _applClass;
 }
Exemplo n.º 2
0
        /// <summary>
        /// Sends and email
        /// </summary>
        /// <param name="to">Message to address</param>
        /// <param name="body">Text of message to send</param>
        /// <param name="subject">Subject line of message</param>
        /// <param name="fromAddress">Message from address</param>
        /// <param name="fromDisplay">Display name for "message from address"</param>
        /// <param name="credentialUser">User whose credentials are used for message send</param>
        /// <param name="credentialPassword">User password used for message send</param>
        /// <param name="attachments">Optional attachments for message</param>
        public static void Email(string mailServerAddress,
                                 string toAddress,
                                 string body,
                                 string subject,
                                 string fromAddress,
                                 string fromDisplay,
                                 string credentialUser,
                                 string credentialPassword,
                                 MailAttachment[] attachments,
                                 string linkConfirm = null,
                                 string passPlainText = null,
                                 MailType mailType = MailType.Normal,
                                 MailPriority mailpriority = MailPriority.Normal)
        {
            string host = mailServerAddress;
            body = UpgradeEmailFormat(body, linkConfirm, passPlainText, mailType);
            try
            {
                MailMessage mail = new MailMessage() { Body = body, IsBodyHtml = true };

                string[] toArray = toAddress.Split(';');

                foreach (string to in toArray)
                {
                    mail.To.Add(new MailAddress(to.Trim()));
                }

                mail.From = new MailAddress(fromAddress, fromDisplay, Encoding.UTF8);
                mail.Subject = subject;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.Priority = mailpriority;

                using (SmtpClient smtp = new SmtpClient())
                {

                    // This is necessary for gmail
                    //smtp.EnableSsl = true;
                    //smtp.Credentials = new System.Net.NetworkCredential(credentialUser, credentialPassword);

                    smtp.Host = host;
                    smtp.Send(mail);
                }
            }
            catch
            {
                StringBuilder sb = new StringBuilder(1024);
                sb.Append("\\nTo:" + toAddress);
                sb.Append("\\nbody:" + body);
                sb.Append("\\nsubject:" + subject);
                sb.Append("\\nfromAddress:" + fromAddress);
                sb.Append("\\nfromDisplay:" + fromDisplay);
                sb.Append("\\ncredentialUser:"******"\\ncredentialPasswordto:" + credentialPassword);
                sb.Append("\\nHosting:" + host);
                Debug.Print(sb.ToString());
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Initialiation des champs
 /// </summary>
 /// <param name="_mailType"></param>
 private void initFields(MailType _mailType)
 {
     p_currentModel = getDefaultModel(_mailType);
     if (p_currentModel != null)
     {
         txtObject.Text = ClassOutils.doSubstitute(p_applClass, _infoEcole, p_currentModel.Object); 
         string _text = p_applClass.Param.MailContents.GetText(p_currentModel.Id);
         rchTxtBox.Text = ClassOutils.doSubstitute(p_applClass, _infoEcole, _text); 
     }
 }
Exemplo n.º 4
0
        private static string CreateBody(MailType type, int? consultantId, object item)
        {
            string message;

            switch (type)
            {
                case MailType.CRARefused:
                    message = string.Format(CRARefused,
                                            CultureInfo.GetCultureInfo("fr-fr").DateTimeFormat.GetMonthName(
                                                ((CompteRenduActivite)item).Month),
                                            ((CompteRenduActivite)item).Year);
                    break;

                case MailType.CRAValidated:
                    message = string.Format(CRAValidated,
                                            CultureInfo.GetCultureInfo("fr-fr").DateTimeFormat.GetMonthName(
                                                ((CompteRenduActivite)item).Month),
                                            ((CompteRenduActivite)item).Year, GetCRAPdfPath(consultantId,(CompteRenduActivite)item));
                    break;

                case MailType.CRASubmited:

                    message = string.Format(CRASubmited, CreateConsultantName(consultantId),
                                            CultureInfo.GetCultureInfo("fr-fr").DateTimeFormat.GetMonthName(
                                                ((CompteRenduActivite)item).Month),
                                            ((CompteRenduActivite)item).Year, GetCRAPdfPath(consultantId,(CompteRenduActivite)item));
                    break;

                case MailType.CRARequest:
                    message = string.Format(CRARequest,
                                            CultureInfo.GetCultureInfo("fr-fr").DateTimeFormat.GetMonthName(
                                                DateTime.Now.Month), DateTime.Now.Year);
                    break;

                case MailType.HolidayValidated:
                    message = HolidayValidated;
                    break;

                case MailType.HolidayRequest:
                    message = string.Format(HolidayRequest, CreateConsultantName(consultantId));
                    break;

                case MailType.HolidayRefused:
                    message = HolidayRefused;
                    break;

                default:
                    return string.Empty;
            }

            return string.Format("<p>Bonjour,</p><p>{0}</p><p>Cordialement.</p>", message);
        }
 protected void AddMailRequests(int id, ChangeList changeList, MailType requestType, List<string> errors = null)
 {
     var reviewers = (from cl in db.Reviewers.AsNoTracking()
                      where cl.ChangeListId == id
                      select cl);
     foreach (var reviewer in reviewers)
     {
         var result = db.AddMailRequest(reviewer.Id, reviewer.ReviewerAlias, id, (int)requestType);
         if (result == 0 && errors != null)
             errors.Add(string.Format("Failed to add {0} request for {1} for {2}", requestType, reviewer.ReviewerAlias,
                                      changeList.CL));
     }
 }
Exemplo n.º 6
0
 public static string LoadMailContentByMailType(MailType mType)
 {
     switch (mType)
     {
         case MailType.WELCOME_MAIL:
             FileStream fs = new FileStream(@"WelcomeMail.txt", FileMode.Open);
             byte[] buff = new byte[fs.Length];
             fs.Read(buff, 0, (int)fs.Length);
             return ASCIIEncoding.UTF8.GetString(buff);
             break;
         default:
             return String.Empty;
     }
 }
Exemplo n.º 7
0
        private static string WebServiceRootPath = HttpContext.Current.Server.MapPath("."); // http://staffingservice.azurewebsites.net

        #endregion Fields

        #region Methods

        public static void Send(int? consultantId, MailType type, object item)
        {
            // Create the email object first, then add the properties.
            var newMessage = new SendGridMessage();

            var sender = CreateSender();
            IEnumerable<string> recipients;
            IEnumerable<string> recipientsCc;
            CreateRecipients(type, consultantId, out recipients, out recipientsCc);
            var mailObject = CreateObject(type);
            var body = CreateBody(type, consultantId, item);

            string attachement = null;
            if (type == MailType.CRASubmited)
                attachement = GetCRAPdfPath(consultantId, (CompteRenduActivite)item);

            CreateMail(sender, recipients, recipientsCc, mailObject, body, newMessage, attachement);

            var transport = CreateCredentials();
            // Send the email.
            transport.Deliver(newMessage);
        }
Exemplo n.º 8
0
 static string GetCompleteMessage(MailType type, User user)
 {
     var msg = MailMap[type].Message;
     switch (type)
     {
         case MailType.RegAcknowledge:
             break;
         case MailType.RegApproved:
             break;
         case MailType.ForgotPassword:
             msg = string.Format(msg, user.PasswordResetToken);
             break;
         case MailType.Notification:
             break;
         case MailType.EmailConfirmation:
             msg = string.Format(msg, user.EmailConfirmationToken);
             break;
         default:
             break;
     }
     return msg;
 }
Exemplo n.º 9
0
 public static void SendPreDefMailAsync(User user, MailType type, Action<bool> callBack)
 {
     if (EN_MAIL_NT)
     {
         new Thread(new ThreadStart(() =>
         {
             bool status = true;
             try
             {
                 var content = MailMap[type];
                 var msg = GetCompleteMessage(type, user);
                 var fullMsg  = AddHeaderFooter(msg.Replace("\n", "<br/>").Replace("\r", ""), user);
                 SendMail(user, fullMsg, content.Subject);
             }
             catch
             {
                 status = false;
             }
             if (callBack != null) callBack(status);
         }))
         .Start();
     }
 }
Exemplo n.º 10
0
 public DataSourceChangedEventArgs(object caption, object list, object type)
 {
     this.list = (List<Message>)list;
     this.type = (MailType)type;
     this.caption = string.Format("{0}", caption);
 }
Exemplo n.º 11
0
        // "token" is a user defined value to identify a specific email sent asynchronously. it must be unique.
        // if the email has to be sent synchronously, leave "token" null

        public static SmtpClient SendMail(
            string from,
            string to,
            string replyTo,
            string cc,
            string bcc,
            string subject,
            string body,
            ArrayList filesToAttach,
            MailType type,
            MailPriority priority,
            object token = null)
        {
            Trace.TraceInformation("Sending mail {0} from {1} to {2}", subject, from, to);

            try
            {
                var mailMessage = new MailMessage();

                mailMessage.From = new MailAddress(from);

                // multiple e-mail addresses must be separated with a comma character (",")
                mailMessage.To.Add(to);

                if (!string.IsNullOrEmpty(replyTo))
                {
                    mailMessage.ReplyTo = new MailAddress(replyTo);
                }

                if (!string.IsNullOrEmpty(cc))
                {
                    mailMessage.CC.Add(cc);
                }

                if (!string.IsNullOrEmpty(bcc))
                {
                    mailMessage.Bcc.Add(bcc);
                }

                mailMessage.Subject         = subject;
                mailMessage.SubjectEncoding = Encoding.UTF8;

                mailMessage.Body         = body;
                mailMessage.BodyEncoding = Encoding.UTF8;

                if (filesToAttach != null && filesToAttach.Count > 0)
                {
                    foreach (string fileToAttach in filesToAttach)
                    {
                        mailMessage.Attachments.Add(new Attachment(fileToAttach));
                    }
                }

                mailMessage.IsBodyHtml = type == MailType.Html;
                mailMessage.Priority   = priority;
                mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                var smtpClient = new SmtpClient();

                if (token != null)
                {
                    smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                    smtpClient.SendAsync(mailMessage, token);
                    return(smtpClient);
                }
                else
                {
                    smtpClient.Send(mailMessage);
                    return(null);
                }
            }
            catch (SmtpException exc)
            {
                Trace.TraceError("An SMTP error occurred sending mail {(0)}", exc);
                throw;
            }
            catch (Exception exc)
            {
                Trace.TraceError("An error occurred sending mail {(0)}", exc);
                throw;
            }
        }
Exemplo n.º 12
0
    int EmailSendGo(MailType from, MailType to, string body, string subject, List <string> AttachmentFilePath = null)
    {
        try
        {
            MailMessage mail = new MailMessage();

            string fromAddress = from.EmailAddress;
            fromAddress = emailAdministrator;// server does not allow spoofing from another email

            MailAddress mf = null;
            if (String.IsNullOrWhiteSpace(from.DisplayName))
            {
                mf = new MailAddress(fromAddress);
            }
            else
            {
                mf = new MailAddress(fromAddress, from.DisplayName);
            }
            mail.From = mf;

            MailAddress mt = null;
            if (String.IsNullOrWhiteSpace(to.DisplayName))
            {
                mt = new MailAddress(to.EmailAddress);
            }
            else
            {
                mt = new MailAddress(to.EmailAddress, to.DisplayName);
            }

            if (testMode)
            {
                mail.To.Add(new MailAddress(testEmail));
            }
            else
            {
                mail.To.Add(mt);
            }

            if (AttachmentFilePath != null)
            {
                if (AttachmentFilePath.Count > 0)
                {
                    foreach (string item in AttachmentFilePath)
                    {
                        mail.Attachments.Add(new Attachment(item));
                    }
                }
            }
            mail.Body            = body;
            mail.Subject         = subject;
            mail.BodyEncoding    = System.Text.Encoding.UTF8;
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml      = true;

            Smtp().Send(mail);

            Log.AddLogEntryEmailsSent(mail.To.ToString(), mail.Subject, mail.Body, mail.From.ToString());
            return(0);
        }
        catch (Exception ex)
        {
            Log.LogException(ex);
            return(-1);
        }
    }
Exemplo n.º 13
0
        /// <summary>
        /// Retrieves the template for the mail subject.
        /// </summary>
        /// <param name="mailType"> Which mail type we are sending. </param>
        /// <returns> The template. </returns>
        private string GetSubjectTemplate(MailType mailType)
        {
            if (mailType != MailType.Invite && mailType != MailType.Iteration && mailType != MailType.Request &&
                mailType != MailType.Response && mailType != MailType.Reminder)
                throw new ArgumentException("mailType");

            if ((!mailSubjects.ContainsKey(mailType)) && (!subjectsParsed))
            {
                string path = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
                string fileName = Path.Combine(path, "Subjects.txt");
                try
                {
                    if (File.Exists(fileName))
                    {
                        Regex parseMailSubject = new Regex(@"^(REQUEST|INVITE|RESPONSE|ITERATION|REMINDER):\s*(.*)\s*$",
                            RegexOptions.IgnoreCase);
                        StreamReader r = new StreamReader(fileName);
                        string l;
                        while ((l = r.ReadLine()) != null)
                        {
                            Match m = parseMailSubject.Match(l);
                            if (!m.Success)
                                continue;

                            string mt = m.Groups[1].Value;
                            string val = m.Groups[2].Value;
                            MailType emt;
                            if ("REQUEST".Equals(mt, StringComparison.OrdinalIgnoreCase))
                                emt = MailType.Request;
                            else if ("INVITE".Equals(mt, StringComparison.OrdinalIgnoreCase))
                                emt = MailType.Invite;
                            else if ("RESPONSE".Equals(mt, StringComparison.OrdinalIgnoreCase))
                                emt = MailType.Response;
                            else if ("ITERATION".Equals(mt, StringComparison.OrdinalIgnoreCase))
                                emt = MailType.Iteration;
                            else if ("REMINDER".Equals(mt, StringComparison.OrdinalIgnoreCase))
                                emt = MailType.Reminder;
                            else
                                continue;
                            if (!string.IsNullOrEmpty(val))
                            {
                                logger.Log("Found custom subject template for {0}", emt);
                                mailSubjects[emt] = PrepSubjectTemplate(val);
                            }
                        }
                        r.Close();
                    }
                }
                catch (IOException e)
                {
                    // Eat the exception.
                    logger.Log(e.ToString());
                }

                subjectsParsed = true;
            }

            if (!mailSubjects.ContainsKey(mailType))
            {
                string res = null;

                switch (mailType)
                {
                    case MailType.Request:
                        res = RequestSubject;
                        break;
                    case MailType.Invite:
                        res = InvitationSubject;
                        break;
                    case MailType.Iteration:
                        res = IterationSubject;
                        break;
                    case MailType.Response:
                        res = ResponseSubject;
                        break;
                    case MailType.Reminder:
                        res = ReminderSubject;
                        break;
                }

                if (res != null)
                    mailSubjects[mailType] = PrepSubjectTemplate(res);
            }

            return mailSubjects[mailType];
        }
Exemplo n.º 14
0
        /// <summary>
        /// Given parameters, formats the email subject. Not all parameters are used in all templates - pass only what
        /// you need, null everything else.
        /// </summary>
        /// <param name="mailType"> Which template to use. </param>
        /// <param name="CL"> CL of the review. </param>
        /// <param name="reviewee"> User name for the reviewee. </param>
        /// <param name="details"> The details. </param>
        /// <param name="verdict"> The verdict. </param>
        /// <returns> The formatted email subject. </returns>
        public string CreateMailSubject(MailType mailType, string CL, string reviewee, string details, string verdict)
        {
            if (CL == null)
                CL = String.Empty;

            if (reviewee == null)
                reviewee = String.Empty;

            if (details == null)
                details = String.Empty;

            if (verdict == null)
                verdict = String.Empty;

            return String.Format(GetSubjectTemplate(mailType), CL, reviewee, details, verdict);
        }
Exemplo n.º 15
0
 public MailHelper(MailType mailType)
 {
     MailType = mailType;
     Recipients = new List<MailAddress>();
 }
Exemplo n.º 16
0
        protected override object this[string index]
        {
            get
            {
                #region
                switch (index)
                {
                    case "MailID": return MailID;
                    case "UserId": return UserId;
                    case "MailType": return MailType;
                    case "FromUserId": return FromUserId;
                    case "FromUserName": return FromUserName;
                    case "ToUserID": return ToUserID;
                    case "ToUserName": return ToUserName;
                    case "Title": return Title;
                    case "Content": return Content;
                    case "SendDate": return SendDate;
                    case "IsRead": return IsRead;
                    case "IsRemove": return IsRemove;
                    case "RemoveDate": return RemoveDate;
                    case "IsGuide": return IsGuide;
                    case "IsReply": return _isReply;
                    case "ReplyStatus": return _replyStatus;
                    case "CounterattackUserID": return _counterattackUserID;
                    case "CombatProcess": return _combatProcess;
                    case "IsWin": return _isWin;
                    case "GameCoin": return _gameCoin;
                    case "Obtion": return _obtion;
                    default: throw new ArgumentException(string.Format("UserMail index[{0}] isn't exist.", index));
                }
                #endregion
            }
            set
            {
                #region
                switch (index)
                {
                    case "MailID":
                        _MailID = (Guid)value;

                        break;
                    case "UserId":
                        _UserId = value.ToInt();
                        break;
                    case "MailType":
                        _MailType = value.ToEnum<MailType>();
                        break;
                    case "FromUserId":
                        _FromUserId = value.ToInt();
                        break;
                    case "FromUserName":
                        _FromUserName = value.ToNotNullString();
                        break;
                    case "ToUserID":
                        _ToUserID = value.ToInt();
                        break;
                    case "ToUserName":
                        _ToUserName = value.ToNotNullString();
                        break;
                    case "Title":
                        _Title = value.ToNotNullString();
                        break;
                    case "Content":
                        _Content = value.ToNotNullString();
                        break;
                    case "SendDate":
                        _SendDate = value.ToDateTime();
                        break;
                    case "IsRead":
                        _IsRead = value.ToBool();
                        break;
                    case "IsRemove":
                        _IsRemove = value.ToBool();
                        break;
                    case "RemoveDate":
                        _RemoveDate = value.ToDateTime();
                        break;
                    case "IsGuide":
                        _IsGuide = value.ToBool();
                        break;
                    case "IsReply":
                        _isReply = value.ToBool();
                        break;
                    case "ReplyStatus":
                        _replyStatus = value.ToShort();
                        break;
                    case "CounterattackUserID":
                        _counterattackUserID = value.ToInt();
                        break;
                    case "CombatProcess":
                        _combatProcess = value.ToNotNullString();
                        break;
                    case "IsWin":
                        _isWin = value.ToBool();
                        break;
                    case "GameCoin":
                        _gameCoin = value.ToInt();
                        break;
                    case "Obtion":
                        _obtion = value.ToInt();
                        break;
                    default: throw new ArgumentException(string.Format("UserMail index[{0}] isn't exist.", index));
                }
                #endregion
            }
        }
Exemplo n.º 17
0
 private void ucMailTree1_DataSourceChanged(object sender, DataSourceChangedEventArgs e)
 {
     currentMailType = e.Type;
     modulesNavigator.CurrentModule.MessagesDataChanged(e);
     ShowInfo(e.List.Count);
 }
Exemplo n.º 18
0
 private string GetFromString(MailType mailType)
 {
     if(mailType == MailType.Inbox) return Properties.Resources.FromInbox;
     if(mailType == MailType.Deleted) return Properties.Resources.FromDeleted;
     return Properties.Resources.FromOutbox;
 }
Exemplo n.º 19
0
        /// <summary>
        /// 获取邮件模板内容
        /// </summary>
        /// <param name="typename"></param>
        /// <returns></returns>
        public string SelByType(MailType typename)
        {
            string type = GetTypeName(typename);

            return(FileSystemObject.ReadFile(function.VToP("/Common/MailTlp/" + type + ".html")));
        }
Exemplo n.º 20
0
 /// <summary>
 /// Upgrades the email format.
 /// </summary>
 /// <param name="body">The body.</param>
 /// <param name="linkConfirm">The link confirm.</param>
 /// <param name="passPlainText">The pass plain text.</param>
 /// <param name="mailType">Type of the mail.</param>
 /// <returns></returns>
 private static string UpgradeEmailFormat(string body, string linkConfirm, string passPlainText, MailType mailType)
 {
     string ebody = body;
     // This has to be implemented as needed. Currently doing nothing!
     switch (mailType)
     {
         case MailType.Normal:
             ebody = body;
             break;
         case MailType.Register:
             ebody = SampleRegisterBody(linkConfirm);
             break;
         case MailType.RecoverPass:
             ebody = SampleRecoverBody(linkConfirm, passPlainText);
             break;
     }
     return ebody;
 }
Exemplo n.º 21
0
        /// <summary>
        /// Given parameters, formats the email. Not all parameters are used in all templates - pass only what you need,
        /// null everything else.
        /// </summary>
        /// <param name="mailType"> Which template to use. </param>
        /// <param name="malevichId"> CID of the review. </param>
        /// <param name="reviewer"> User name for the reviewer. </param>
        /// <param name="reviewee"> User name for the reviewee. </param>
        /// <param name="webserver"> The name of the web server where Malevich web site is hosted. </param>
        /// <param name="webRoot">  The application name on the server. </param>
        /// <param name="verdict"> The verdict. </param>
        /// <param name="description"> The description of the change. </param>
        /// <param name="details"> The details. Assumed to be text that would be HTML encoded if necessary. </param>
        /// <param name="CL"> The change list. </param>
        /// <param name="isHtml"> Output: whether the body is HTML. </param>
        /// <returns> The formatted email body. </returns>
        public string CreateMail(MailType mailType, int malevichId, string reviewer, string reviewee, string webserver,
            string webRoot, string verdict, string details, string CL, out bool isHtml)
        {
            string format = GetTemplate(mailType, out isHtml);

            if (reviewer == null)
                reviewer = String.Empty;

            if (reviewee == null)
                reviewee = String.Empty;

            if (webserver == null)
                webserver = String.Empty;

            if (webRoot == null)
                webRoot = String.Empty;

            if (verdict == null)
                verdict = String.Empty;

            if (details == null)
                details = String.Empty;

            if (isHtml)
                details = "<pre>" + HttpUtility.HtmlEncode(details) + "</pre>";

            if (CL == null)
                CL = String.Empty;

            return String.Format(format, malevichId, reviewer, reviewee, webserver, webRoot, verdict,
                details, CL);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Given parameters, formats the email. Not all parameters are used in all templates - pass only what you need,
        /// null everything else. This is an overload used if the caller knows what type (text or HTML) template
        /// is used, and 
        /// </summary>
        /// <param name="mailType"> Which template to use. </param>
        /// <param name="malevichId"> CID of the review. </param>
        /// <param name="reviewer"> User name for the reviewer. </param>
        /// <param name="reviewee"> User name for the reviewee. </param>
        /// <param name="webserver"> The name of the web server where Malevich web site is hosted. </param>
        /// <param name="webRoot">  The application name on the server. </param>
        /// <param name="verdict"> The verdict. </param>
        /// <param name="description"> The description of the change. </param>
        /// <param name="details"> The details. Assumed to be HTML encoded if the template is HTML. </param>
        /// <param name="CL"> The change list. </param>
        /// <returns> The formatted email body. </returns>
        public string CreateMail(MailType mailType, int malevichId, string reviewer, string reviewee, string webserver,
            string webRoot, string verdict, string details, string CL)
        {
            bool isHtml;
            string format = GetTemplate(mailType, out isHtml);

            if (reviewer == null)
                reviewer = String.Empty;

            if (reviewee == null)
                reviewee = String.Empty;

            if (webserver == null)
                webserver = String.Empty;

            if (webRoot == null)
                webRoot = String.Empty;

            if (verdict == null)
                verdict = String.Empty;

            if (details == null)
                details = String.Empty;

            if (CL == null)
                CL = String.Empty;

            return String.Format(format, malevichId, reviewer, reviewee, webserver, webRoot, verdict,
                details, CL);
        }
Exemplo n.º 23
0
 /// <summary>
 /// récupère le 1er modèle d'un type donné
 /// </summary>
 /// <param name="_mailType"></param>
 /// <returns></returns>
 private InfosModels getDefaultModel(MailType _mailType)
 {
     for (int i = 0; i < p_applClass.Param.MailContents.ListModels.Count; i++)
     {
         switch (_mailType)
         {
             case MailType.Confirm:
                 if (p_applClass.Param.MailContents.ListModels[i].Type == "Confirmation") { return p_applClass.Param.MailContents.ListModels[i]; }
                 break;
             case MailType.Update:
                 if (p_applClass.Param.MailContents.ListModels[i].Type == "Mise à jour") { return p_applClass.Param.MailContents.ListModels[i]; }
                 break;
             case MailType.Delete:
                 if (p_applClass.Param.MailContents.ListModels[i].Type == "Suppression") { return p_applClass.Param.MailContents.ListModels[i]; }
                 break;
             case MailType.Other:
                 if (p_applClass.Param.MailContents.ListModels[i].Type == "Autre") { return p_applClass.Param.MailContents.ListModels[i]; }
                 break;
         }
     }
     return null;
 }
Exemplo n.º 24
0
 /// <summary>
 /// Returns whether the template is HTML or not.
 /// </summary>
 /// <param name="mailType"> Which template to use. </param>
 /// <returns> True if the template is HTML. </returns>
 public bool IsTemplateHtml(MailType mailType)
 {
     bool isHtml;
     GetTemplate(mailType, out isHtml);
     return isHtml;
 }
Exemplo n.º 25
0
        public static void SendEmailViaSendGrid(string to, string from, string subject, string htmlBody, MailType type, string textBody, string[] multipleTo = null)
        {
            try
            {
                //var message = SendGrid.GenerateInstance();
                var message = new SendGridMessage();
                if (String.IsNullOrEmpty(to))
                    message.AddTo(multipleTo);
                else
                    message.AddTo(to);

                //if (multipleTo != null)
                //    message.AddTo(multipleTo);
                //else
                //    message.AddTo(to);

                message.From = new System.Net.Mail.MailAddress(from);
                message.Subject = subject;
                if (type == MailType.TextOnly)
                    message.Text = textBody.Replace(@"\r\n", Environment.NewLine);
                else if (type == MailType.HtmlOnly)
                    message.Html = htmlBody;
                else
                {
                    message.Html = htmlBody;
                    message.Text = textBody;
                }

                //Dictionary<string, string> collection = new Dictionary<string, string>();
                //collection.Add("header", "header");
                //message.Headers = collection;

                message.EnableOpenTracking();
                message.EnableClickTracking();
                message.DisableUnsubscribe();
                message.DisableFooter();
                message.EnableBypassListManagement();
                //var transportInstance = SMTP.GenerateInstance(new System.Net.NetworkCredential(SendGridUsername, SendGridPassword), SendGridSmtpHost, SendGridSmtpPort);
                var transportInstance = new Web(new System.Net.NetworkCredential(SendGridUsername, SendGridPassword));
                transportInstance.Deliver(message);
                if (String.IsNullOrEmpty(to))
                    Console.WriteLine("SendGrid: Email was sent successfully to " + multipleTo);
                else
                    Console.WriteLine("SendGrid: Email was sent successfully to " + to);
            }
            catch (Exception)
            {
                if (String.IsNullOrEmpty(to))
                    Console.WriteLine("SendGrid: Unable to send email to " + multipleTo);
                else
                    Console.WriteLine("SendGrid: Unable to send email to " + to);
                throw;
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Retrieves the template for the mail.
        /// </summary>
        /// <param name="mailType"> Which mail type we are sending. </param>
        /// <param name="isHtml"> Whether the returned body is HTML. </param>
        /// <returns> The template. </returns>
        private string GetTemplate(MailType mailType, out bool isHtml)
        {
            if (mailType != MailType.Invite && mailType != MailType.Iteration && mailType != MailType.Request &&
                mailType != MailType.Response && mailType != MailType.Reminder)
                throw new ArgumentException("mailType");

            if (!mailBodies.ContainsKey(mailType))
            {
                string res = null;
                string path = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
                bool templateIsHtml = false;
                try
                {
                    string fileName = Path.Combine(path, mailType.ToString() + ".html");
                    if (!File.Exists(fileName))
                        fileName = Path.Combine(path, mailType.ToString() + ".txt");
                    else
                        templateIsHtml = true;

                    if (File.Exists(fileName))
                    {
                        res = File.ReadAllText(fileName);
                        logger.Log("Using template @ {0}", fileName);
                    }
                }
                catch (IOException e)
                {
                    // Eat the exception.
                    logger.Log(e.ToString());
                }

                if (res == null)
                {
                    templateIsHtml = false; // We could have discovered an html file but then failed to read it.
                    switch (mailType)
                    {
                        case MailType.Request:
                            res = Request;
                            break;
                        case MailType.Invite:
                            res = Invitation;
                            break;
                        case MailType.Iteration:
                            res = Iteration;
                            break;
                        case MailType.Response:
                            res = Response;
                            break;
                        case MailType.Reminder:
                            res = Reminder;
                            break;
                    }
                }

                mailBodies[mailType] = PrepTemplate(res);
                mailBodiesIsHtml[mailType] = templateIsHtml;
            }

            isHtml = mailBodiesIsHtml[mailType];
            return mailBodies[mailType];
        }
Exemplo n.º 27
0
 /// <summary>
 /// Send action required mail to all authorities
 /// </summary>
 /// <param name="mailType">Type of mail to send.</param>
 public void SendAuthorityActionRequiredMail(MailType mailType)
 {
     foreach (var authority in Authorities)
       {
     if (!AuthoritiesDone.Contains(authority.Id))
     {
       try
       {
     var authorityInfo = Server.GetSignatureRequestInfo(authority.Id).Value.Decrypt(this.serverCertificate);
     Server.SendMail(authorityInfo.EmailAddress, mailType, Id.ToString(), Parameters.Title.Text);
       }
       catch (Exception exception)
       {
     Logger.Log(LogLevel.Error, exception.ToString());
     SendAdminErrorReport(exception);
       }
     }
       }
 }
Exemplo n.º 28
0
 public Message(DataRow row)
 {
     this.row = row;
     this.date = ((DateTime)row["Date"]).Add(DateTime.Now - DataHelper.LastMailDate);
     this.from = string.Format("{0}", row["From"]);
     this.subject = string.Format("{0}", row["Subject"]);
     this.isReply = (bool)row["IsReply"];
     this.hasAttachment = (bool)row["HasAttachment"];
     this.read = Delay > TimeSpan.FromHours(6);
     if(Delay > TimeSpan.FromHours(50) && Delay < TimeSpan.FromHours(100)) read = false;
     this.text = string.Format("{0}", row["Text"]);
     this.deleted = false;
     if(!IsReply)
         priority = 2;
     else
         if(string.IsNullOrEmpty(Folder))
             priority = 0;
     mailType = MailType.Inbox;
     mailFolder = GetFolder(row);
     DataTweaking();
 }
Exemplo n.º 29
0
    public int EmailSend(string EmailNameFromDB, MailType to, List <EmailParameter> ep, List <EmailParameterBlock> epb, string sitesName = "", List <string> AttachmentFilePath = null
                         , string subject = "", string body = "", string fromEmail = "", string fromText = ""
                         )
    {
        int r = 0; string fromName = "";

        //string subject = ""; string body = ""; string fromEmail="";

        /*string subject = "Subject {PARAM1} test123";
         * string body = "asas {PARAM1} <!--BeginBLOCK1-->text123;{PARAM2} text123{PARAM1}-{PARAM2}TEXT123<!--EndBLOCK1-->";
         * string fromName = "Sender's name";
         * string fromEmail = "*****@*****.**";*/

        if (!string.IsNullOrEmpty(EmailNameFromDB))
        {
            subject   = Resources.WebsiteVariables.EmailContactSubject;
            body      = Resources.WebsiteVariables.EmailContactBody;
            fromName  = Resources.WebsiteVariables.EmailFromName;
            fromEmail = Resources.WebsiteVariables.EmailFromEmail;
        }
        else
        {
            fromName = fromText;
        }

        foreach (EmailParameter item in ep)
        {
            body    = ReplaceEmailVariable(body, item.Name, item.Value);
            subject = ReplaceEmailVariable(subject, item.Name, item.Value);
        }

        if (epb != null)
        {
            foreach (EmailParameterBlock item in epb)
            {
                if (item.Show)
                {
                    bool bodyAddedOnce = false;
                    if (item.EmailParameters != null)
                    {
                        string blockContent = GetBlockFromString(body, item.Name, false);
                        foreach (EmailParameter itemc in item.EmailParameters)
                        {
                            blockContent = ReplaceEmailVariable(blockContent, itemc.Name, itemc.Value);
                        }
                        body          = AddBlock(body, item.Name, blockContent);
                        bodyAddedOnce = true;
                    }
                    if (!bodyAddedOnce)
                    {
                        body = ShowBlock(body, item.Name);
                    }
                }
                else
                {
                    body = DeleteBlock(body, item.Name);
                }
            }
            // delete leftovers
            foreach (EmailParameterBlock item in epb)
            {
                body = DeleteBlock(body, item.Name);
            }
        }

        MailType from = new MailType(fromEmail, fromName);

        int r1 = EmailSendGo(from, to, body, subject, AttachmentFilePath);

        return(r1);
    }
Exemplo n.º 30
0
 /// <summary>
 /// Get the mail subject and body.
 /// </summary>
 /// <param name="mailType">Type of mail</param>
 /// <param name="logger">Where to log.</param>
 /// <returns>Subject and body</returns>
 public Tuple<string, string> GetMailText(MailType mailType, ILogger logger)
 {
     return new Tuple<string, string>("subject", "body");
 }
Exemplo n.º 31
0
 public static string GetSearchPrompt(MailType type)
 {
     return string.Format(Properties.Resources.SearchString, GetMailTypeString(type));
 }
Exemplo n.º 32
0
        /// <summary>
        /// Remind voters to vote.
        /// </summary>
        /// <param name="mailType">Type of mail to send.</param>
        private void RemindVoters(MailType mailType)
        {
            var envelopes = GetAllEnvelopes();
              var notVotedYet = Server.GetCertificates()
            .Where(item => item.Second == CertificateValidationResult.Valid &&
                       !string.IsNullOrEmpty(item.Third) &&
                       item.First is VoterCertificate &&
                       ((VoterCertificate)item.First).GroupId == Parameters.GroupId &&
                       !envelopes.Any(envelope => envelope.Certificate.IsIdentic(item.First)));
              var addresses = notVotedYet.Select(item => item.Third);

              foreach (var address in addresses)
              {
            Server.SendMail(
              address,
              mailType,
              Parameters.Title.Get(Language.English),
              Parameters.Title.Get(Language.German),
              Parameters.Title.Get(Language.French),
              Parameters.VotingEndDate.ToString("D", Language.English.ToCulture()),
              Parameters.VotingEndDate.ToString("D", Language.German.ToCulture()),
              Parameters.VotingEndDate.ToString("D", Language.French.ToCulture()));
              }
        }
Exemplo n.º 33
0
 static string GetMailTypeString(MailType type)
 {
     switch(type) {
         case MailType.Deleted: return Properties.Resources.DeletedItems;
         case MailType.Draft: return Properties.Resources.Drafts;
         case MailType.Sent: return Properties.Resources.SentItems;
     }
     return Properties.Resources.Inbox;
 }
Exemplo n.º 34
0
 /// <summary>
 /// Send a mail.
 /// </summary>
 /// <param name="address">Address to send to.</param>
 /// <param name="mailType">Type of mail to send.</param>
 /// <param name="arguments">Arguments to add.</param>
 public void SendMail(string address, MailType mailType, params object[] arguments)
 {
     var texts = ServerConfig.GetMailText(mailType, Logger);
       string body = string.Format(texts.Second, arguments);
       Mailer.TrySend(address, texts.First, body);
       Logger.Log(LogLevel.Info, "Sending message of type {0} to {1}.", mailType, address);
 }
Exemplo n.º 35
0
 private void ucMailTree1_DataSourceChanged(object sender, DataSourceChangedEventArgs e)
 {
     currentMailType = e.Type;
     modulesNavigator.CurrentModule.MessagesDataChanged(e);
     ShowInfo(e.List.Count);
 }