Ejemplo n.º 1
0
 public void SendMail(MailInput m)
 {
     using (var da = dam.Create())
     {
         if (UserId == -1)
         {
             throw new InvalidOperationException();
         }
         foreach (var mt in m.ToIds)
         {
             if (da.FromUserProfileSelectCountById(mt) == 0)
             {
                 throw new InvalidOperationException();
             }
         }
         var Time = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture);
         var v    = new DB.Mail {
             Title = m.Title, FromId = UserId, Time = Time, Content = m.Content
         };
         da.FromMailInsertOne(v);
         var Id = v.Id;
         da.FromMailToInsertMany(m.ToIds.Select(mt => new DB.MailTo {
             Id = Id, ToId = mt
         }).ToList());
         da.FromMailOwnerInsertMany(m.ToIds.Select(mt => new DB.MailOwner {
             Id = Id, OwnerId = mt, IsNew = true, Time = Time
         }).ToList());
         da.FromMailAttachmentInsertMany(m.Attachments.Select(ma => new DB.MailAttachment {
             Id = Id, Name = ma.Name, Content = ma.Content.ToArray()
         }).ToList());
         da.Complete();
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Mail Generator => Generates mail with main mail parameters and set ready to send with SmtpClient.
        /// </summary>
        /// <param name="mail">MailInput</param>
        /// <returns>MailMessage</returns>
        private MailMessage MailMessageGenerator(MailInput mail)
        {
            var mailMessage = new MailMessage();

            #region Subject, Body, From
            mailMessage.Subject = mail.Subject;
            mailMessage.From    = new MailAddress("*****@*****.**");
            mailMessage.Body    = mail.Body;
            #endregion

            #region To
            if (mail.To != null && mail.To.Count > 0)
            {
                foreach (var to in mail.To)
                {
                    if (IsValid(to))
                    {
                        mailMessage.To.Add(new MailAddress(to));
                        _to += to + ";";
                    }
                }
            }
            #endregion

            #region CC
            if (mail.CC != null && mail.CC.Count > 0)
            {
                foreach (var cc in mail.CC)
                {
                    if (IsValid(cc))
                    {
                        mailMessage.To.Add(new MailAddress(cc));
                        _cc += cc + ";";
                    }
                }
            }
            #endregion

            #region BCC
            if (mail.BCC != null && mail.BCC.Count > 0)
            {
                foreach (var bcc in mail.BCC)
                {
                    if (IsValid(bcc))
                    {
                        mailMessage.To.Add(new MailAddress(bcc));
                        _bcc += bcc + ";";
                    }
                }
            }
            #endregion

            return(mailMessage);
        }
Ejemplo n.º 3
0
        public void MailSend(MailInput mail)
        {
            _mailDBOperations = new MailDBOperations();

            try
            {
                MailMessage _mail  = new MailMessage();
                SmtpClient  client = new SmtpClient();
                client.EnableSsl = false;
                client.Host      = "xx.xx.xx.xx";
                string smtpUserName = "******";
                string smtpPassword = "******";

                client.Port        = 587;
                client.Credentials = new NetworkCredential(smtpUserName, smtpPassword);

                _mail            = MailMessageGenerator(mail);
                _mail.IsBodyHtml = true;
                client.ServicePoint.Expect100Continue = false;
                client.Send(_mail);

                var mailLog = new Mail
                {
                    Subject      = mail.Subject,
                    Body         = mail.Body,
                    MailFrom     = mail.From,
                    MailTo       = _to,
                    MailCc       = _cc,
                    MailBcc      = _bcc,
                    CreationTime = DateTime.Now
                };

                _mailDBOperations.Create(mailLog);
            }
            catch (Exception ex)
            {
                var mailLog = new Mail
                {
                    Subject  = mail.Subject,
                    Body     = mail.Body,
                    MailFrom = mail.From,
                    MailTo   = _to,
                    MailCc   = _cc,
                    MailBcc  = _bcc
                };

                _mailDBOperations.Log(ex, mailLog);
            }
        }
Ejemplo n.º 4
0
        private static void Send()
        {
            List <int> ToIds;

            while (true)
            {
                Console.WriteLine("请输入收件人,以空格隔开:");
                var Line = Console.ReadLine().Trim();
                if (Line == "")
                {
                    Console.WriteLine("至少要有一个收件人。");
                    continue;
                }
                var Parts         = Regex.Split(Line, @"\s+");
                var Users         = Parts.Select(p => new { Id = s.GetUserIdByName(p), Name = p }).ToArray();
                var UsersNotExist = Users.Where(u => !u.Id.HasValue).ToArray();
                if (UsersNotExist.Length > 0)
                {
                    Console.WriteLine("收件人" + String.Join(" ", UsersNotExist.Select(u => u.Name).ToArray()) + "不存在。");
                    continue;
                }
                ToIds = Users.Select(u => u.Id.Value).ToList();
                break;
            }
            Console.WriteLine("请输入标题:");
            var Title = Console.ReadLine();

            var Lines = new List <String>();

            Console.WriteLine("请输入内容,输入单个的点号(.)结束:");
            while (true)
            {
                var Line = Console.ReadLine();
                if (Line == ".")
                {
                    break;
                }
                Lines.Add(Line);
            }
            var Content = String.Join("\r\n", Lines.ToArray()) + "\r\n";

            List <MailAttachment> Attachments;

            while (true)
            {
                Console.WriteLine("请输入当前文件夹下的附件名,以空格隔开:");
                var Line = Console.ReadLine().Trim();
                if (Line == "")
                {
                    Attachments = new List <MailAttachment> {
                    };
                    break;
                }
                var Parts               = Regex.Split(Line, @"\s+");
                var AttachmentNames     = Parts.Select(p => new { Exist = File.Exists(p), Name = p }).ToArray();
                var AttachmentsNotExist = AttachmentNames.Where(a => !a.Exist).ToArray();
                if (AttachmentsNotExist.Length > 0)
                {
                    Console.WriteLine("文件" + String.Join(" ", AttachmentsNotExist.Select(a => a.Name).ToArray()) + "不存在。");
                    continue;
                }
                Attachments = AttachmentNames.Select(a => new MailAttachment {
                    Name = a.Name, Content = new List <Byte>(File.ReadAllBytes(a.Name))
                }).ToList();
                break;
            }

            var Mail = new MailInput
            {
                Title       = Title,
                ToIds       = ToIds,
                Content     = Content,
                Attachments = Attachments
            };

            s.SendMail(Mail);
        }
Ejemplo n.º 5
0
 public ActionResult Mail(MailInput input)
 {
     var config = Configs.mailConfigs.Where(s => s.Id == input.ConfigId);
     //MailHelper.SendMail(config,)
 }
Ejemplo n.º 6
0
        public void SendMail(MailInput mail)
        {
            //validation
            if (mail.To == "")
            {
                throw new Exception("Please enter an E-Mail address to 'To' parameter!");
            }
            try
            {
                if (mail.To.Contains(';') == false)
                {
                    var addr = new System.Net.Mail.MailAddress(mail.To);
                }
                else
                {
                    foreach (string item in mail.To.Split(';'))
                    {
                        if (item != "")
                        {
                            var addr = new System.Net.Mail.MailAddress(item);
                        }
                    }
                }

                if (mail.CC != null)
                {
                    if (mail.CC.Contains(';') == false)
                    {
                        var addr = new System.Net.Mail.MailAddress(mail.CC);
                    }
                    else
                    {
                        foreach (string item in mail.CC.Split(';'))
                        {
                            if (item != "")
                            {
                                var addr = new System.Net.Mail.MailAddress(item);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("One of the receipent mail addresses are not valid.");
            }

            if (mail.ConnectionMethod == null)
            {
                throw new Exception("Please select a connection method.");
            }


            if (mail.MailType == null)
            {
                throw new Exception("Please select a mail type.");
            }
            //prepare object instance
            MailSend ms = new MailSend();

            if (mail.MailTemplateId != null)
            {
                if (string.IsNullOrEmpty(this.ConnectionString))
                {
                    throw new Exception("Template stucture is only available with db connection.");
                }
                List <IDataParameter> paramlist = new List <IDataParameter>();
                paramlist.Add(new CustomParameter("id", mail.MailTemplateId));
                List <MailTemplate> mtlist = qm.GetQueryResult <MailTemplate>("GetMailTemplate", paramlist);
                if (mtlist.Count == 0)
                {
                    throw new Exception("Mail Template has not been found on db!");
                }
                else
                {
                    MailTemplate mt        = mtlist[0];
                    string[]     variables = null;

                    string body = File.ReadAllText(mt.TemplateText);
                    if (mt.Variables != "" && mt.Variables.Contains(","))
                    {
                        variables = mt.Variables.Split(',');
                    }
                    if (mt.QueryType == "select")
                    {
                        DataTable dt = qm.GetQueryResultDataTableDirect(mt.Query, null);
                        if (dt.Rows.Count > 0)
                        {
                            string itr = "";
                            if (body.Contains("##for") && body.Contains("##endfor"))
                            {
                                Regex           rgx   = new Regex("##for(\n|.)*##endfor");
                                MatchCollection mtcol = rgx.Matches(body);
                                foreach (Match mtc in mtcol)
                                {
                                    if (mtc.Success)
                                    {
                                        itr = mtc.Value;

                                        string newstr  = itr;
                                        string lastStr = "";
                                        foreach (DataRow dr in dt.Rows)
                                        {
                                            foreach (string vr in variables)
                                            {
                                                newstr = newstr.Replace("#" + vr, dr[vr].ToString());
                                            }
                                            lastStr = lastStr + newstr;
                                            newstr  = itr;
                                        }
                                        body = body.Replace(itr, lastStr);
                                    }
                                }
                            }

                            DataRow drow = dt.Rows[0];
                            foreach (string vr in variables)
                            {
                                body = body.Replace("#" + vr, drow[vr].ToString());
                            }
                            body = body.Replace("##for", "").Replace("##endfor", "");
                        }
                    }
                    else if (mt.QueryType == "execute")
                    {
                        int result = qm.ExecuteQueryText(mt.Query);
                    }
                    else
                    {
                        throw new Exception("Please choose querytype between select and execute options.");
                    }



                    ms.Body = body;
                }
            }
            else
            {
                ms.Body = mail.Body;
            }

            ms.FilePath   = mail.AttachPath;
            ms.MailType   = Convert.ToInt16(mail.MailType);
            ms.MailStatus = 1;
            ms.Module     = "";
            ms.Sender     = mail.From;
            ms.SendDate   = mail.SendDate;
            ms.Subject    = mail.Subject;
            ms.ToAddress  = mail.To;
            ms.CC         = mail.CC;
            ms.InsertDate = DateTime.Now;
            if (ms.SendDate == null)
            {
                ms.SendDate = DateTime.Now;
            }

            //insert to sendmail

            if (mail.ConnectionMethod == ConnectionMethod.DataBase)
            {
                if (ConnectionString == "")
                {
                    throw new Exception("Altough your connection method is Database. Your connection string is empty!. Please enter valid database connection string into constructor method.");
                }
                mc.InsertMailDB(ms);
            }
            else if (mail.ConnectionMethod == ConnectionMethod.WebApi)
            {
                if (AccessKey == "")
                {
                    throw new Exception("Altough your connection method is Web Api. Your AccessKey is empty!. Please enter valid Access Key  into constructor method.");
                }
                mc.InsertMailWS(ms);
            }
        }