Ejemplo n.º 1
0
 /// <summary>
 /// send one mail
 /// </summary>
 /// <param name="mail">email model</param>
 /// <param name="smtp">smtp model</param>
 /// <param name="sync">sync send or not, false(web ap), console(true)</param>
 public static void Send(MailDto mail, SmtpDto smtp = null, bool sync = false)
 {
     Sends(new List <MailDto>()
     {
         mail
     }, smtp, sync);
 }
Ejemplo n.º 2
0
 //send one mail
 private static void SendMail(MailDto mail, SmtpDto smtp = null)
 {
     SendMails(new List <MailDto>()
     {
         mail
     }, smtp);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// 添加邮件服务器
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task <string> AddAsync(SmtpDto dto)
        {
            var entity = _mapper.Map <SmtpDto, SmtpEntity>(dto);

            entity.Init();
            //entity.CreateUserId=
            var dbSet = _context.Smtps;

            dbSet.Add(entity);
            return(await _context.SaveChangesAsync() > 0 ? entity.Id : string.Empty);
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Add(SmtpDto dto)
        {
            if (ModelState.IsValid)
            {
                var result = await _SmtpService.AddAsync(dto);

                if (result.IsNotBlank())
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(dto));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// convert emailDto & smtp to mailMessage object
        /// </summary>
        /// <param name="email"></param>
        /// <param name="smtp"></param>
        /// <returns></returns>
        public static MailMessage DtoToMsg(EmailDto email, SmtpDto smtp = null)
        {
            if (smtp == null)
            {
                smtp = _Fun.Smtp;
            }

            var utf8   = Encoding.GetEncoding("utf-8");
            var sender = new MailAddress(_Str.IsEmpty(smtp.Id) ? smtp.FromEmail : smtp.Id);  //real sender
            var from   = new MailAddress(_Str.IsEmpty(smtp.FromEmail) ? smtp.Id : smtp.FromEmail, smtp.FromName, utf8);

            return(DtoToMsgByArg(email, utf8, sender, from));
        }
Ejemplo n.º 6
0
        //send many mails
        public static void Sends(List <MailDto> mails, SmtpDto smtp = null, bool sync = false)
        {
            //change receiver to tester if need !!
            var mail     = new MailDto();// = null;
            var testMode = !string.IsNullOrEmpty(_Fun.Config.TesterMail);

            if (testMode)
            {
                mail         = mails[0];
                mail.ToUsers = StrToUsers(_Fun.Config.TesterMail);
                mail.CcUsers = null;
            }

            //sync = true;    //temp add
            if (sync)
            {
                if (testMode)
                {
                    SendMail(mail, smtp);
                }
                else
                {
                    SendMails(mails, smtp);
                }
            }
            else
            {
                if (testMode)
                {
                    var thread = new Thread(delegate()
                    {
                        SendMail(mail, smtp);
                    });
                    thread.Start();
                }
                else
                {
                    /*
                     * Task.Factory.StartNew(() =>
                     * {
                     *  SendMails(mails, smtp);
                     * });
                     */
                    var thread = new Thread(delegate()
                    {
                        SendMails(mails, smtp);
                    });
                    thread.Start();
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// convert emailDtos to mailMessages
        /// </summary>
        /// <param name="emails"></param>
        /// <param name="smtp"></param>
        /// <returns></returns>
        public static List <MailMessage> DtosToMsgs(List <EmailDto> emails, SmtpDto smtp = null)
        {
            if (smtp == null)
            {
                smtp = _Fun.Smtp;
            }

            var msgs   = new List <MailMessage>();
            var utf8   = Encoding.GetEncoding("utf-8");
            var sender = new MailAddress(_Str.IsEmpty(smtp.Id) ? smtp.FromEmail : smtp.Id);  //real sender
            var from   = new MailAddress(_Str.IsEmpty(smtp.FromEmail) ? smtp.Id : smtp.FromEmail, smtp.FromName, utf8);

            foreach (var email in emails)
            {
                msgs.Add(DtoToMsgByArg(email, utf8, sender, from));
            }

            return(msgs);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// send mails by emailDtos asynchronus
        /// </summary>
        /// <param name="emails"></param>
        /// <param name="smtp"></param>
        public static async Task SendByDtosAsync(List <EmailDto> emails, SmtpDto smtp = null)
        {
            //change receiver to tester if need !!
            //var email = new EmailDto();// = null;
            var testMode = _Str.NotEmpty(_Fun.Config.TesterEmail);

            if (testMode)
            {
                var email = emails[0];
                email.ToUsers = StrToUsers(_Fun.Config.TesterEmail);
                email.CcUsers = null;
                emails        = new List <EmailDto>()
                {
                    email
                };
            }

            //send
            await SendByMsgsAsync(DtosToMsgs(emails, smtp), smtp);
        }
Ejemplo n.º 9
0
        //send mails, send one by one for security reason
        private static void SendMails(List <MailDto> mails, SmtpDto smtp = null)
        {
            //check
            if (smtp == null)
            {
                smtp = _Fun.Smtp;
            }

            //var smtp = smtp0.Value;
            //send
            try
            {
                var client = new SmtpClient()
                {
                    Host = smtp.Host,
                    Port = smtp.Port,
                    UseDefaultCredentials = false,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    Credentials           = new System.Net.NetworkCredential(smtp.Id, smtp.Pwd),
                    EnableSsl             = smtp.Ssl,
                    Timeout = 30000,
                };

                //string encode = "utf-8";
                var utf8   = Encoding.GetEncoding("utf-8");
                var sender = new MailAddress(_Str.IsEmpty(smtp.Id) ? smtp.FromEmail : smtp.Id);  //real sender
                var from   = new MailAddress(_Str.IsEmpty(smtp.FromEmail) ? smtp.Id : smtp.FromEmail, smtp.FromName, utf8);
                foreach (var mail in mails)
                {
                    var msg = new MailMessage()
                    {
                        SubjectEncoding = utf8,
                        BodyEncoding    = utf8, //or will get random code !!
                        Subject         = mail.Subject,
                        Body            = mail.Body,
                        IsBodyHtml      = true,
                        Sender          = sender,
                        From            = from,
                        //Sender = new MailAddress(_Str.IsEmpty(smtp.Id) ? smtp.FromEmail : smtp.Id),  //real sender
                        //From = new MailAddress(_Str.IsEmpty(smtp.FromEmail) ? smtp.Id : smtp.FromEmail, smtp.FromName, utf8),
                    };

                    //add image, use cid(better than base64 !!)
                    if (mail.ImageIds != null && mail.ImageIds.Count > 0)
                    {
                        for (var i = 0; i < mail.ImageIds.Count; i++)
                        {
                            var imageHtml = string.Format("<html><body><img src=cid:{0}/><br></body></html>", mail.ImageIds[i]);
                            var altView   = AlternateView.CreateAlternateViewFromString(imageHtml, null, MediaTypeNames.Text.Html);

                            var linkSrc = new LinkedResource(mail.ImagePaths[i], MediaTypeNames.Image.Jpeg);
                            linkSrc.ContentId = Guid.NewGuid().ToString();
                            altView.LinkedResources.Add(linkSrc);

                            //MailMessage mail = new MailMessage();
                            msg.AlternateViews.Add(altView);
                        }
                    }

                    //attach files
                    if (mail.Files != null)
                    {
                        foreach (var file in mail.Files)
                        {
                            if (File.Exists(file))
                            {
                                var attach = new Attachment(file);
                                attach.Name = _File.GetFileName(file);  //否則email附檔會出現路徑
                                msg.Attachments.Add(attach);
                            }
                        }
                    }

                    if (mail.ToUsers != null)
                    {
                        foreach (var user in mail.ToUsers)
                        {
                            msg.To.Clear();
                            msg.To.Add(user);
                            client.Send(msg);   //call sync method here!!
                        }
                    }

                    /*
                     * if (mail.CcUsers != null)
                     * {
                     *  foreach (var user in mail.CcUsers)
                     *      msg.CC.Add(user);
                     * }
                     */
                }//for

                client.Dispose();
            }
            catch (Exception ex)
            {
                var error = "Mail failed: " + ex.Message;
                _Log.Error(error, false);    //false here!!
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// send one mail by emailDto
 /// </summary>
 /// <param name="email">email model</param>
 /// <param name="smtp">smtp model</param>
 /// <param name="sync">sync send or not, false(web ap), console(true)</param>
 public static async Task SendByDtoAsync(EmailDto email, SmtpDto smtp = null)
 {
     await SendByDtosAsync(new List <EmailDto>() { email }, smtp);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// send mails, send one by one for security reason
        /// </summary>
        /// <param name="msgs"></param>
        /// <param name="smtp"></param>
        public static async Task SendByMsgsAsync(List <MailMessage> msgs, SmtpDto smtp = null, bool sendImage = true)
        {
            //check
            //error = ""; //initial
            if (smtp == null)
            {
                smtp = _Fun.Smtp;
            }

            //set _emailImagePairs if need
            if (sendImage && _emailImagePairs == null)
            {
                _emailImagePairs = new List <IdStrDto>();
                if (!_Str.IsEmpty(_Fun.Config.EmailImagePairs))
                {
                    var values = _Fun.Config.EmailImagePairs.Split(',');
                    for (var i = 0; i < values.Length; i += 2)
                    {
                        _emailImagePairs.Add(new IdStrDto()
                        {
                            Id  = values[i],
                            Str = values[i + 1],
                        });
                    }
                }
            }

            //send email
            try
            {
                //set smtp
                var client = new SmtpClient()
                {
                    Host = smtp.Host,
                    Port = smtp.Port,
                    UseDefaultCredentials = false,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    Credentials           = new System.Net.NetworkCredential(smtp.Id, smtp.Pwd),
                    EnableSsl             = smtp.Ssl,
                    Timeout = 30000,
                };

                //add images & send
                foreach (var msg in msgs)
                {
                    if (sendImage)
                    {
                        MsgAddImages(msg, _emailImagePairs);
                    }
                    await client.SendMailAsync(msg);
                }

                client.Dispose();
            }
            catch (Exception ex)
            {
                //var error = "_Email.cs SendByMsgsSync() failed: " + ex.InnerException.Message;
                var error = _Str.NotEmpty(ex.Message) ? ex.Message :
                            (ex.InnerException != null) ? ex.InnerException.Message :
                            "Email Error !!";
                await _Log.ErrorAsync("_Email.cs SendByMsgsAsync() failed: " + error, false);    //false here, not mailRoot, or endless roop !!
            }
        }
Ejemplo n.º 12
0
        /*
         * /// <summary>
         * /// send by MailMessage
         * /// </summary>
         * /// <param name="msg"></param>
         * /// <param name="smtp"></param>
         * public static void SendByMsg(MailMessage msg, SmtpDto smtp = null)
         * {
         *  SendByMsgs(new List<MailMessage>() { msg }, smtp);
         * }
         *
         * /// <summary>
         * /// send mails async, send one by one for security reason
         * /// </summary>
         * /// <param name="msgs"></param>
         * /// <param name="smtp"></param>
         * public static void SendByMsgs(List<MailMessage> msgs, SmtpDto smtp = null)
         * {
         *  //async send email
         *  var thread = new Thread(delegate ()
         *  {
         *      SendByMsgsAsync(msgs, smtp);
         *  });
         *  thread.Start();
         * }
         */

        /// <summary>
        /// send email
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="smtp"></param>
        /// <param name="sendImage"></param>
        /// <returns></returns>
        public static async Task SendByMsgAsync(MailMessage msg, SmtpDto smtp = null, bool sendImage = true)
        {
            await SendByMsgsAsync(new List <MailMessage>() { msg }, smtp, sendImage);
        }
Ejemplo n.º 13
0
        //session type(web only), 1:session, 2:redis, 3:custom(config must set SessionService field, use Activator)
        //public static int SessionServiceType = 1;
        #endregion

        /*
         * //constructor
         * static _Fun()
         * {
         * }
         */

        /// <summary>
        /// initial db environment for Ap with db function !!
        /// </summary>
        public static void Init(IServiceProvider di, DbTypeEnum dbType = DbTypeEnum.MSSql,
                                AuthTypeEnum authType = AuthTypeEnum.None, bool dynamicLocale = false)
        {
            //set instance variables
            _di            = di;
            _dbType        = dbType;
            _authType      = authType;
            _dynamicLocale = dynamicLocale;

            #region set smtp
            var smtp = Config.Smtp;
            if (smtp != "")
            {
                try
                {
                    var cols = smtp.Split(',');
                    Smtp = new SmtpDto()
                    {
                        Host      = cols[0],
                        Port      = int.Parse(cols[1]),
                        Ssl       = bool.Parse(cols[2]),
                        Id        = cols[3],
                        Pwd       = cols[4],
                        FromEmail = cols[5],
                        FromName  = cols[6]
                    };
                }
                catch
                {
                    _Log.Error("config Smtp is wrong(7 cols): Host,Port,Ssl,Id,Pwd,FromEmail,FromName");
                }
            }
            #endregion

            #region set DB variables
            //0:select, 1:order by, 2:start row(base 0), 3:rows count
            switch (_dbType)
            {
            case DbTypeEnum.MSSql:
                DbDtFormat = "yyyy-MM-dd HH:mm:ss";
                //JsDtFormat = "yyyy/M/d HH:mm:ss";

                //for sql 2012, more easy
                //note: offset/fetch not sql argument
                ReadPageSql   = @"
select {0} {1}
offset {2} rows fetch next {3} rows only
";
                DeleteRowsSql = "delete {0} where {1} in ({2})";
                break;

            case DbTypeEnum.MySql:
                DbDtFormat = "YYYY-MM-DD HH:mm:SS";

                ReadPageSql = @"
select {0} {1}
limit {2},{3}
";
                //TODO: set delete sql for MySql
                //DeleteRowsSql =
                break;

            case DbTypeEnum.Oracle:
                DbDtFormat = "YYYY/MM/DD HH24:MI:SS";

                //for Oracle 12c after(same as mssql)
                ReadPageSql = @"
Select {0} {1}
Offset {2} Rows Fetch Next {3} Rows Only
";
                //TODO: set delete sql for Oracle
                //DeleteRowsSql =
                break;
            }
            #endregion
        }