Exemplo n.º 1
0
        public static bool SendSenha(string from, string to, string subject, string mensagem)
        {
            System.Net.Mail.SmtpClient s = null;
            try
            {
                s = new System.Net.Mail.SmtpClient("smtp.live.com", 587);
                s.EnableSsl = true;
                s.UseDefaultCredentials = false;
                s.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Projeto032015");
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(
                    new System.Net.Mail.MailAddress(from),
                    new System.Net.Mail.MailAddress(to));
                message.Body = mensagem;
                message.BodyEncoding = Encoding.UTF8;
                message.Subject = subject;
                message.SubjectEncoding = Encoding.UTF8;
                s.Send(message);
                s.Dispose();

                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (s != null)
                    s.Dispose();
            }
        }
Exemplo n.º 2
0
        public static bool Send(string nome, string from, string subject, string mensagem)
        {
            System.Net.Mail.SmtpClient s = null;
            try
            {
                s                       = new System.Net.Mail.SmtpClient("smtp.live.com", 587);
                s.EnableSsl             = true;
                s.UseDefaultCredentials = false;
                s.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "M@is$angue");
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(
                    new System.Net.Mail.MailAddress(from),
                    new System.Net.Mail.MailAddress("*****@*****.**"));
                message.Body            = "De: " + nome + "\n" + "Email: " + from + "\n" + "\n" + "Mensagem: " + "\n" + mensagem;
                message.BodyEncoding    = Encoding.UTF8;
                message.Subject         = subject;
                message.SubjectEncoding = Encoding.UTF8;
                s.Send(message);
                s.Dispose();

                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                if (s != null)
                {
                    s.Dispose();
                }
            }
        }
Exemplo n.º 3
0
        public static bool Send(string from, string subject, string body)
        {
            System.Net.Mail.SmtpClient s = null;
            try
            {
                s = new System.Net.Mail.SmtpClient("smtp.live.com", 587);
                s.EnableSsl = true;
                s.UseDefaultCredentials = false;
                s.Credentials = new System.Net.NetworkCredential("seu email", "sua senha");
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(
                    new System.Net.Mail.MailAddress("seu email"),
                    new System.Net.Mail.MailAddress("seu email"));
                message.Body = "De: " + from + "\n" + body;
                message.BodyEncoding = Encoding.UTF8;
                message.Subject = subject;
                message.SubjectEncoding = Encoding.UTF8;
                s.Send(message);
                s.Dispose();

                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (s != null)
                    s.Dispose();
            }
        }
Exemplo n.º 4
0
        public static bool Send(string nome, string from, string subject, string mensagem)
        {
            System.Net.Mail.SmtpClient s = null;
            try
            {
                s = new System.Net.Mail.SmtpClient("smtp.live.com", 587);
                s.EnableSsl = true;
                s.UseDefaultCredentials = false;
                s.Credentials = new System.Net.NetworkCredential("*****@*****.**", "M@is$angue");
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(
                new System.Net.Mail.MailAddress(from),
                new System.Net.Mail.MailAddress("*****@*****.**"));
                message.Body = "De: " +nome+ "\n"+ "Email: "+from + "\n" + "\n"+ "Mensagem: "+"\n"+mensagem;
                message.BodyEncoding = Encoding.UTF8;
                message.Subject = subject;
                message.SubjectEncoding = Encoding.UTF8;
                s.Send(message);
                s.Dispose();

                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (s != null)
                    s.Dispose();
            }
        }
Exemplo n.º 5
0
        public void EnviarMail(string destinatario, string asunto, string mensaje)
        {
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add(destinatario);
            msg.Subject         = asunto;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body            = mensaje;
            msg.BodyEncoding    = System.Text.Encoding.UTF8;
            msg.From            = new System.Net.Mail.MailAddress("*****@*****.**");

            //Cliente Mail
            System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient();
            cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "tesisperros");
            cliente.EnableSsl   = true;
            cliente.Port        = 587;
            cliente.Host        = "smtp.gmail.com";
            try
            {
                cliente.Send(msg);
                Console.WriteLine("Correo enviado con éxito");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error al enviar el mail");
            }
            finally
            {
                msg.Dispose();
                cliente.Dispose();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="member"></param>
        /// <param name="url"></param>
        public static void sendEmall(Member member, String url)
        {
            string mailTitle = "テストメールです。";
            string mailText  = member.LastName + "  " + member.FirstName + "さん" + Environment.NewLine +
                               "このメールは、テストです。" + Environment.NewLine + url;

            //MailMessageの作成
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(member.Email, member.Email, mailTitle, mailText);
            System.Net.Mail.SmtpClient  sc  = new System.Net.Mail.SmtpClient();

            //SMTPサーバーなどを設定する
            sc.Host           = "smtp.gmail.com";
            sc.Port           = 587;
            sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            //ユーザー名とパスワードを設定する
            sc.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Narita1981");

            //SSLを使用する
            sc.EnableSsl = true;
            //メッセージを送信する
            sc.Send(msg);

            //後始末
            msg.Dispose();
            //後始末(.NET Framework 4.0以降)
            sc.Dispose();
        }
Exemplo n.º 7
0
            /// <summary>
            /// Send message with error included
            /// </summary>
            /// <param name="message">The caption message to be mailed</param>
            /// <param name="host">The host to be connected</param>
            /// <param name="errcode">Error code indentification</param>
            /// <returns>Send message with error</returns>
            public async Task SendMessageThreadSafe(string message, string smtphost, int port, long errcode)
            {
                try
                {
                    System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient(smtphost, port);
                    smtpclient.Port                  = 587;
                    smtpclient.Host                  = "smtp.gmail.com";
                    smtpclient.EnableSsl             = true;
                    smtpclient.Timeout               = 10000;
                    smtpclient.DeliveryMethod        = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpclient.UseDefaultCredentials = false;
                    smtpclient.Credentials           = new System.Net.NetworkCredential("puchiruzuki", "ac/dc03[]");

                    System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**", "Mainstream UMS Bug track system", "Bug track number: " + errcode + ".\n" + message);

                    smtpclient.Send(mm);

                    MessageBox(new IntPtr(0), "Bug Registrado com sucesso!\n Bug error track " + errcode + ".", message, 0);
                    //Free resources
                    smtpclient.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox(new IntPtr(0), "Send message error", ex.Message, 0);
                    throw;
                }
            }
        private static void sendEmailWithSendGrid(SendGrid sendGrid, EmailMessage message)
        {
            // We want this method to use the SendGrid API (https://github.com/sendgrid/sendgrid-csharp), but as of 20 June 2014 it looks like the SendGrid Web API
            // does not support CC recipients!

            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient("smtp.sendgrid.net", 587);

            try {
                smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtpClient.Credentials    = new System.Net.NetworkCredential(sendGrid.UserName, sendGrid.Password);

                using (var m = new System.Net.Mail.MailMessage()) {
                    message.ConfigureMailMessage(m);
                    try {
                        smtpClient.Send(m);
                    }
                    catch (System.Net.Mail.SmtpException e) {
                        throw new EmailSendingException("Failed to send an email message using SendGrid.", e);
                    }
                }
            }
            finally {
                smtpClient.Dispose();
            }
        }
Exemplo n.º 9
0
        private static void SmtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            // Get the DTOMailMessage object
            DTOMailMessage objDTOMailMessage = (DTOMailMessage)e.UserState;

            System.Net.Mail.SmtpClient objSmtpClient = (System.Net.Mail.SmtpClient)sender;

            // Get MailMessage
            System.Net.Mail.MailMessage objMailMessage = objDTOMailMessage.MailMessage;

            if (e.Error != null)
            {
                // Log to the System Log
                Log.InsertSystemLog(
                    objDTOMailMessage.DefaultConnection,
                    Constants.EmailError, "",
                    $"Error: {e.Error.GetBaseException().Message} - To: {objMailMessage.To} Subject: {objMailMessage.Subject}");
            }
            else
            {
                // Log the Email
                LogEmail(objDTOMailMessage.DefaultConnection, objMailMessage);

                objMailMessage.Dispose();
                objSmtpClient.Dispose();
            }
        }
Exemplo n.º 10
0
        private void button4_Click(object sender, EventArgs e)
        {
            //メッセージボックスを表示する
            DialogResult result = MessageBox.Show("メールを送信しますか?",
                                                  "写真メール送信",
                                                  MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question,
                                                  MessageBoxDefaultButton.Button2);

            // ダイアログでOKを押したときだけ送信処理
            if (result == DialogResult.Yes)
            {
                //MailMessageの作成
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                //送信者
                msg.From = new System.Net.Mail.MailAddress(myMailAddress);
                //宛先
                msg.To.Add(new System.Net.Mail.MailAddress(toMailAddress));
                //.NET Framework 3.5以前では、以下のようにする
                //msg.ReplyTo = new System.Net.Mail.MailAddress("*****@*****.**");
                //Sender
                //msg.Sender = new System.Net.Mail.MailAddress("*****@*****.**");

                //件名
                msg.Subject = "こんにちは";
                //本文
                msg.Body = toMailMessage;

                //メールの配達が遅れたとき、失敗したとき、正常に配達されたときに通知する
                msg.DeliveryNotificationOptions =
                    System.Net.Mail.DeliveryNotificationOptions.Delay |
                    System.Net.Mail.DeliveryNotificationOptions.OnFailure |
                    System.Net.Mail.DeliveryNotificationOptions.OnSuccess;

                //画像をファイルで添付する
                System.Net.Mail.Attachment attach1 = new System.Net.Mail.Attachment("Image.jpg");
                //動画の場合
                //System.Net.Mail.Attachment attach1 = new System.Net.Mail.Attachment("anoto.avi");
                msg.Attachments.Add(attach1);

                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
                //SMTPサーバーなどを設定する
                sc.Host = myMailServer;
                sc.Port = 587;
                //GMail認証
                sc.Credentials = new System.Net.NetworkCredential(myMailID, myMailPassword);
                //SSL
                sc.EnableSsl      = true;
                sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                //メッセージを送信する
                sc.Send(msg);

                //後始末
                msg.Dispose();
                //後始末(.NET Framework 4.0以降)
                sc.Dispose();
            }
        }
Exemplo n.º 11
0
        public static void AutoEmailSend(string recipient, string subject, string content)
        {
            System.Net.Mail.SmtpClient smtp =
                new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

            smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "bavvjfsnecmjnhhy");
            smtp.EnableSsl   = true;
            smtp.Send("*****@*****.**", $"{recipient}", $"{subject}", $"{content}");
            smtp.Dispose();
        }
Exemplo n.º 12
0
        public static bool EnviarCorreo(string para, string asunto, string mensaje)
        {
            try
            {
                string RemitenteNombre = "InnovaSchool";
                string RemitenteCorreo = "*****@*****.**";
                string RemitenteClave  = "contraseña";
                string RemitenteHost   = "smtp.gmail.com";
                int    RemitentePuerto = 587;
                bool   RemitenteSSL    = true;


                System.Net.Mail.MailMessage Mail       = new System.Net.Mail.MailMessage();
                System.Net.Mail.SmtpClient  ObjectSmtp = new System.Net.Mail.SmtpClient();

                Mail.From = new System.Net.Mail.MailAddress(RemitenteCorreo, RemitenteNombre);

                /*Agregamos los correos a enviar To*/
                if (!string.IsNullOrEmpty(para))
                {
                    foreach (string item in para.Split(','))
                    {
                        if (item.Contains("@"))
                        {
                            Mail.To.Add(item);
                        }
                    }
                }

                Mail.Subject      = asunto;
                Mail.Body         = mensaje;
                Mail.BodyEncoding = Encoding.GetEncoding("UTF-8");
                Mail.IsBodyHtml   = true;
                Mail.Priority     = System.Net.Mail.MailPriority.High;

                ObjectSmtp.Host        = RemitenteHost;
                ObjectSmtp.Port        = RemitentePuerto;
                ObjectSmtp.EnableSsl   = RemitenteSSL;
                ObjectSmtp.Credentials = new System.Net.NetworkCredential(RemitenteCorreo, RemitenteClave);


                ObjectSmtp.Send(Mail);

                Mail.Dispose();
                ObjectSmtp.Dispose();

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Attempts to send an email
        /// </summary>
        /// <param name="type">The Type of Email Being Sent</param>
        /// <param name="custom">Whether to Customize the email</param>
        /// <param name="body">If customized, set the html body for the email</param>
        /// <param name="To">If customized, defines the TO field</param>
        /// <param name="ToName">If customized, defines the To name</param>
        /// <returns>Returns a KeyValuePair(bool,string) with success (true/false) and a message from the smtp server</returns>
        public KeyValuePair <bool, string> SendMail(MessageType type, bool custom = false, string body = "", string To = "", string ToName = "New Member")
        {
            if (SetupServer())
            {
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

                mail.Subject    = SUBJECT;
                mail.From       = new System.Net.Mail.MailAddress(FROM, FROM_NAME);
                mail.IsBodyHtml = true;

                if (ToName != "")
                {
                    TO_NAME = ToName;
                }

                if (To == "")
                {
                    mail.To.Add(new System.Net.Mail.MailAddress(TO, TO_NAME));
                }
                else
                {
                    mail.To.Add(new System.Net.Mail.MailAddress(To, TO_NAME));
                }

                if (custom)
                {
                    mail.Body = body;
                }
                else
                {
                    BODY      = GetEmailFilePath(type);
                    mail.Body = BODY;
                }

                try
                {
                    SmtpServer.Send(mail);
                    return(new KeyValuePair <bool, string>(true, "Email sent succesfully"));
                }
                catch (Exception ex)
                {
                    return(new KeyValuePair <bool, string>(false, ex.Message));
                }
                finally
                {
                    SmtpServer.Dispose();
                }
            }
            else
            {
                return(new KeyValuePair <bool, string>(false, "Error Setting UP Email"));
            }
        }
Exemplo n.º 14
0
        private static void OnChange(object source, FileSystemEventArgs e)
        {
            try
            {
                string filePath = e.FullPath;
                List<string> parentDirs = filePath.Split('\\').ToList();
                string userName = parentDirs[7].ToString();
                //This is the directory we are monitoring for change.
                DirectoryInfo info = new DirectoryInfo(@"C:\Program Files (x86)\Avaya\IP Office\Voicemail Pro\VM\Accounts\" + userName);
                userName = userName.Replace(" ", ".");

                Thread.Sleep(1000);

                string email = "Your Email";
                string emailPassword = "******";
                List<FileInfo> files = info.GetFiles().OrderByDescending(p => p.CreationTime).ToList();
                string wavPath = files[0].DirectoryName + "\\" + files[0].ToString();
                string date = DateTime.Now.ToString();

                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                System.Net.Mail.Attachment mail = new System.Net.Mail.Attachment(wavPath);
                //Creating message body
                message.Subject = "A new voicemail has been recieved at: " + date;
                message.Attachments.Add(mail);
                message.To.Add(userName);
                message.From = new System.Net.Mail.MailAddress(email);
                message.Body = "You have recieved a new voicemail. Please see the attached document and have a great day!";
                //setting up SMTP client to be used, in this case basic google.
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");

                smtp.Port = 25;
                smtp.Credentials = new System.Net.NetworkCredential(email, emailPassword);
                smtp.EnableSsl = true;
                smtp.Send(message);
                //A simple console log for the viewers pleasure.
                Console.WriteLine("An email has been sent to " + userName);
                //diposing of objects
                message.Dispose();
                mail.Dispose();
                smtp.Dispose();
            }
            catch
            {
                //if any errors can view log to see which error was caught
                using (StreamWriter writer = new StreamWriter(@"C:\EmailSentErrors\ErrorDoc.txt", true))
                {
                    writer.WriteLine("Error sending email on " + DateTime.Now.ToString());
                    writer.WriteLine("------------------------------------------");
                }
            }
        }
Exemplo n.º 15
0
        //テスト送信ボタン
        private void button3_Click(object sender, EventArgs e)
        {
            //メール関係はサブルーチンで行う
            if (!mailDatacheck())
            {
                return;
            }
            try
            {
                //JISコード
                System.Text.Encoding enc = System.Text.Encoding.GetEncoding(50220);

                //MailMessageの作成
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage("*****@*****.**", m_sendAddress.Text);
                msg.Subject         = m_subject.Text;
                msg.SubjectEncoding = enc;

                //本文と、本文の文字コードを設定する
                msg.Body = "pingToolよりメールテスト送信。";

                msg.BodyEncoding = enc;
                //「content-transfer-encoding」を「7bit」にする
                msg.BodyTransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;

                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
                //SMTPサーバーなどを設定する
                sc.Host = m_smtpServer.Text;
                sc.Port = Int16.Parse(m_smtpPort.Text);

                //ユーザー名とパスワードを設定する(AUTH LOGIN認証)
                if (m_authCheck.Checked)
                {
                    sc.Credentials = new System.Net.NetworkCredential(m_username.Text, m_password.Text);
                }

                sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                //メッセージを送信する
                sc.Send(msg);

                //後始末
                msg.Dispose();
                sc.Dispose();

                MessageBox.Show("メール送信しました。", "pingTool", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("テストメールの送信時にエラーが発生しました。" + ex.Message, "pingTool", MessageBoxButtons.OK, MessageBoxIcon.Error);
                logger.Error("テストメールの送信時にエラーが発生しました。" + ex.Message + " " + ex.StackTrace);
            }
        }
Exemplo n.º 16
0
        public void UseGmail(string EMAIL, string Subject, string Body)
        {
            //建立 SmtpClient 物件 並設定 Gmail的smtp主機及Port
            System.Net.Mail.SmtpClient MySmtp = new System.Net.Mail.SmtpClient("smtp.mail.yahoo.com", 587);

            //設定你的帳號密碼
            MySmtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "dbsmjyuxuycokkat");

            //Gmial 的 smtp 必需要使用 SSL
            MySmtp.EnableSsl = true;

            //發送Email
            MySmtp.Send("*****@*****.**", EMAIL, Subject, Body); MySmtp.Dispose();
        }
Exemplo n.º 17
0
        protected void SendEmail(object sender, EventArgs e)
        {
            System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage();
            correo.From = new System.Net.Mail.MailAddress("*****@*****.**");
            correo.To.Add(this.TextCorreoCliente.Text);
            correo.Subject = "Informe de Compra en AmazonFake";

            string  cod, des;
            int     cant;
            var     items = (DataTable)Session["pedido"];
            decimal total, prec, subtotal, igv;

            des = "";
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                cod = (GridView1.Rows[i].Cells[1].Text);
                //\
                cant = System.Convert.ToInt16(((TextBox)this.GridView1.Rows[i].Cells[0].FindControl("TextBox1")).Text);
                prec = Decimal.Parse(GridView1.Rows[i].Cells[3].Text);
                des += "\r\n" + (GridView1.Rows[i].Cells[2].Text) + " " + "(" + cant + ")" + " " + Convert.ToString(prec) + "\r\n";
                //Actualiza la canasta

                foreach (DataRow objDR in items.Rows)
                {
                    if (objDR["codproducto"].ToString() == cod)
                    {
                        break;
                    }
                }
            }
            try
            {
                correo.Body       = "Estimado " + txtCliente.Text + " Es un gusto informarle que usted ha realizado un pedido en nuestro sitio web por la cantidad de : S/. " + lblTotal.Text + "\r\nEntre los cuales se encuentran\r\n" + des;
                correo.IsBodyHtml = false;
                correo.Priority   = System.Net.Mail.MailPriority.Normal;
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                smtp.Host        = "smtp.gmail.com";
                smtp.Port        = 587;
                smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "egs76$gs");
                smtp.EnableSsl   = true;
                smtp.Send(correo);
                smtp.Dispose();
                Response.Redirect("/Index.aspx");
            }
            catch (Exception ex)
            {
                lbl_Error.Text = ex.Message.ToString();
            }
        }
Exemplo n.º 18
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.Mail.SmtpClient  smtp           = new System.Net.Mail.SmtpClient();
            System.Net.Mail.MailMessage netMailMessage = new System.Net.Mail.MailMessage();
            netMailMessage.IsBodyHtml      = true;
            netMailMessage.Priority        = System.Net.Mail.MailPriority.Normal;
            netMailMessage.SubjectEncoding = Encoding.UTF8;
            netMailMessage.BodyEncoding    = Encoding.UTF8;
            netMailMessage.Subject         = this.textBox6.Text;
            netMailMessage.Body            = this.richTextBox1.Text;
            var toList  = this.textBox5.Text.Split(';');
            var ccList  = this.textBox8.Text.Split(';');
            var bccList = this.textBox9.Text.Split(';');

            netMailMessage.From = new System.Net.Mail.MailAddress(this.textBox3.Text);
            foreach (var mailAddress in toList)
            {
                netMailMessage.To.Add(mailAddress);
            }
            foreach (var mailAddress in ccList)
            {
                netMailMessage.CC.Add(mailAddress);
            }
            foreach (var mailAddress in bccList)
            {
                netMailMessage.Bcc.Add(mailAddress);
            }
            try
            {
                smtp.UseDefaultCredentials = true;
                smtp.Host        = this.textBox1.Text;
                smtp.Port        = Convert.ToInt32(this.textBox2.Text);
                smtp.EnableSsl   = this.checkBox1.Checked;
                smtp.Credentials = new System.Net.NetworkCredential(this.textBox3.Text, this.textBox4.Text);
                smtp.Send(netMailMessage);
                this.richTextBox2.Text = "smtp.Send(netMailMessage) is OK!";
            }
            catch (Exception ex)
            {
                this.richTextBox2.Text = ex.Message + "***" + ex.InnerException + "***" + ex.StackTrace;
                Console.WriteLine(ex);
            }
            finally
            {
                netMailMessage.Dispose();
                smtp.Dispose();
            }
        }
Exemplo n.º 19
0
        public string send(Class_PropertyMail prop)
        {
            try
            {
                //JISコード
                System.Text.Encoding enc = System.Text.Encoding.GetEncoding(50220);

                //MailMessageの作成
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage("*****@*****.**", prop.sendAddress);
                msg.Subject         = prop.subject;
                msg.SubjectEncoding = enc;

                //本文と、本文の文字コードを設定する
                msg.Body = bodyText;

                //文字コード
                msg.BodyEncoding = enc;
                //「content-transfer-encoding」を「7bit」にする
                msg.BodyTransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;

                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();

                //SMTPサーバーなどを設定する
                sc.Host = prop.smtpServer;
                sc.Port = Int16.Parse(prop.smtpPort);

                //ユーザー名とパスワードを設定する(AUTH LOGIN認証)
                if (prop.authCheck.IndexOf("yes", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    sc.Credentials = new System.Net.NetworkCredential(prop.userID, prop.password);
                }

                sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                //メッセージを送信する
                sc.Send(msg);

                //後始末
                msg.Dispose();
                sc.Dispose();
                logger.Info("メールを送信しました。");
                return("メールを送信しました。");
            }
            catch (Exception ex)
            {
                logger.Error("メールの送信時にエラーが発生しました。" + ex.Message + " " + ex.StackTrace);
                return("メールの送信時にエラーが発生しました。");
            }
        }
Exemplo n.º 20
0
        private void EnviarCorreo(String destinatario, Alumno alumno, int id_inscripcion_curso)
        {
            try
            {
                System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage();
                mmsg.To.Add(destinatario);                    //Destinatario
                mmsg.Subject         = "Inscripcion a curso"; //Asunto
                mmsg.SubjectEncoding = System.Text.Encoding.UTF8;


                //mmsg.Bcc.Add(""); //Para enviar copia de correo
                string body = "";
                body += "<p>Buenas noches,</p><p> A continuacion, la lista de cursos a los que se ha inscripto:</p><ul>";

                //foreach (Curso c in InscripcionCurso.ObtenerCursosDeAlumno(alumno))
                foreach (Curso c in Curso.ObtenerCursosInscriptosAlumno(id_inscripcion_curso))
                {
                    body += "<li>" + c.ToString() + "</li>";
                }

                body += "</ul><p>Saludos cordiales</p>";

                mmsg.Body         = body;
                mmsg.BodyEncoding = System.Text.Encoding.UTF8;
                mmsg.IsBodyHtml   = true;
                mmsg.From         = new System.Net.Mail.MailAddress("*****@*****.**"); //correo que envia

                System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient("smtp.gmail.com");

                cliente.Port      = 587;
                cliente.EnableSsl = true;
                //cliente.Host = "smtp.gmail.com";
                cliente.UseDefaultCredentials = true;

                cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "enviarcorreodesdecsharp"); //credenciales


                cliente.Send(mmsg);

                cliente.Dispose();
            }
            catch (Exception)
            {
                //throw;
                MessageBox.Show("Atencion", "Error al enviar correo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 21
0
        private static void sendEmailWithSmtpServer(SmtpServer smtpServer, EmailMessage message)
        {
            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient();

            try {
                if (smtpServer != null)
                {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host           = smtpServer.Server;
                    if (smtpServer.PortSpecified)
                    {
                        smtpClient.Port = smtpServer.Port;
                    }
                    if (smtpServer.Credentials != null)
                    {
                        smtpClient.Credentials = new System.Net.NetworkCredential(smtpServer.Credentials.UserName, smtpServer.Credentials.Password);
                        smtpClient.EnableSsl   = true;
                    }
                }
                else
                {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;

                    var pickupFolderPath = StandardLibraryMethods.CombinePaths(ConfigurationStatics.RedStaplerFolderPath, "Outgoing Dev Mail");
                    Directory.CreateDirectory(pickupFolderPath);
                    smtpClient.PickupDirectoryLocation = pickupFolderPath;
                }

                using (var m = new System.Net.Mail.MailMessage()) {
                    message.ConfigureMailMessage(m);
                    try {
                        smtpClient.Send(m);
                    }
                    catch (System.Net.Mail.SmtpException e) {
                        throw new EmailSendingException("Failed to send an email message using an SMTP server.", e);
                    }
                }
            }
            finally {
                // Microsoft's own dispose method fails to work if Host is not specified, even though Host doesn't need to be specified for operation.
                if (!string.IsNullOrEmpty(smtpClient.Host))
                {
                    smtpClient.Dispose();
                }
            }
        }
 public static void info_mail(string strErrorVisitDate, string infoMailText, string processingContent)
 {
     //MailMessageの作成  (メールアドレス送信アカウント, 送信先メールアドレス, 件名, 本文)
     System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**", "顧客更新システムの更新結果情報", "更新日時:" + strErrorVisitDate + Environment.NewLine +
                                                                       infoMailText + "処理内容" + processingContent);
     System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
     //SMTPサーバーなどを設定する
     sc.Host           = "mail35.heteml.jp";
     sc.Port           = 587;
     sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
     //ユーザー名とパスワードを設定する
     sc.Credentials = new System.Net.NetworkCredential("hanamura", "222222");
     //メッセージを送信する
     sc.Send(msg);
     //後始末
     msg.Dispose();
     //後始末(.NET Framework 4.0以降)
     sc.Dispose();
 }
Exemplo n.º 23
0
        public async Task SendEmailAsync(
            string fromDisplayName,
            string fromEmailaddress,
            string toName,
            string toEmailAddress,
            string subject,
            string message,
            params Attachment[] attachments)
        {
            var email = new MimeMessage();

            email.From.Add(new MailboxAddress(fromDisplayName, fromEmailaddress));
            email.To.Add(new MailboxAddress(toName, toEmailAddress));
            email.Subject = subject;

            var body = new BodyBuilder
            {
                HtmlBody = message
            };

            foreach (var attachment in attachments)
            {
                using (var stream = await attachment.ContentToStreamAsync())
                {
                    body.Attachments.Add(attachment.FileName, stream);
                }
            }
            System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage();
            MyMailMessage.From = new System.Net.Mail.MailAddress(fromEmailaddress);
            MyMailMessage.To.Add(toEmailAddress);// Mail would be sent to this address
            MyMailMessage.Subject = subject;

            MyMailMessage.Body = message.ToString();
            using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(_emailConfiguration.SmtpServer))
            {
                client.Port = _emailConfiguration.SmtpPort;
                client.UseDefaultCredentials = false;
                client.Credentials           = new System.Net.NetworkCredential(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);
                client.EnableSsl             = true;
                client.Send(MyMailMessage);
                client.Dispose();
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// 邮件的发送;发送成功返回null,失败返回失败原因
 /// </summary>
 /// <returns>发送失败则返回错误信息</returns>
 public string Send()
 {
     mSmtpClient = new System.Net.Mail.SmtpClient();
     try
     {
         if (mMailMessage != null)
         {
             //mSmtpClient.Host = "smtp." + mMailMessage.From.Host;
             mSmtpClient.Host = this.mSenderServerHost;
             mSmtpClient.Port = this.mSenderPort;
             mSmtpClient.UseDefaultCredentials = false;
             mSmtpClient.EnableSsl             = this.mEnableSsl;
             if (this.mEnablePwdAuthentication)
             {
                 System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                 //mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                 //NTLM: Secure Password Authentication in Microsoft Outlook Express
                 mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
             }
             else
             {
                 mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
             }
             mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
             mSmtpClient.Send(mMailMessage);
         }
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
     finally
     {
         mSmtpClient.Dispose();
     }
     return(null);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Sending An Email with master mail template.
        /// </summary>
        /// <param name="mailFrom">Mail From.</param>
        /// <param name="mailTo">Mail To.</param>
        /// <param name="mailCC">Mail CC.</param>
        /// <param name="mailBCC">Mail BCC.</param>
        /// <param name="subject">Mail Subject.</param>
        /// <param name="body">Mail Body.</param>
        /// <param name="languageId">Mail Language.</param>
        /// <param name="emailType">Email Type.</param>
        /// <param name="attachment">Mail Attachment.</param>
        /// <param name="mailLogo">Mail Logo</param>
        /// <param name="LoginUrl">Login Url</param>
        /// <param name="attachmentByteList">Attachment byte list for the mail.</param>
        /// <param name="attachmentName">Attachment file name for the mail.</param>
        /// <param name="sender">Sender.</param>
        /// <returns>return send status.</returns>
        public static bool Send(string mailFrom, string mailTo, string mailCC, string mailBCC, string subject, string body, int languageId, EmailType emailType, string attachment, string mailLogo, string LoginUrl, List <byte[]> attachmentByteList = null, string attachmentName = null, string sender = null)
        {
            if (ProjectConfiguration.SkipEmail)
            {
                return(true);
            }

            if (ProjectConfiguration.IsEmailTest)
            {
                mailTo  = ProjectConfiguration.FromEmailAddress;
                mailCC  = string.Empty;
                mailBCC = string.Empty;
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (!string.IsNullOrEmpty(mailFrom))
            {
                mailFrom = mailFrom.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailTo))
            {
                mailTo = mailTo.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailCC))
            {
                mailCC = mailCC.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailBCC))
            {
                mailBCC = mailBCC.Trim(';').Trim(',');
            }

            if (ValidateEmail(mailFrom, mailTo) && (string.IsNullOrEmpty(mailCC) || ValidateEmail(mailCC)) && (string.IsNullOrEmpty(mailBCC) || ValidateEmail(mailBCC)))
            {
                System.Net.Mail.MailMessage mailMesg = new System.Net.Mail.MailMessage();
                mailMesg.From = new System.Net.Mail.MailAddress(mailFrom);
                if (!string.IsNullOrEmpty(mailTo))
                {
                    mailTo = mailTo.Replace(";", ",");
                    mailMesg.To.Add(mailTo);
                }

                if (!string.IsNullOrEmpty(mailCC))
                {
                    mailCC = mailCC.Replace(";", ",");
                    mailMesg.CC.Add(mailCC);
                }

                if (!string.IsNullOrEmpty(mailBCC))
                {
                    mailBCC = mailBCC.Replace(";", ",");
                    mailMesg.Bcc.Add(mailBCC);
                }

                if (!string.IsNullOrEmpty(attachment) && string.IsNullOrEmpty(attachmentName))
                {
                    string[] attachmentArray = attachment.Trim(';').Split(';');
                    foreach (string attachFile in attachmentArray)
                    {
                        try
                        {
                            System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(attachFile);
                            mailMesg.Attachments.Add(attach);
                        }
                        catch
                        {
                        }
                    }
                }
                else if (!string.IsNullOrEmpty(attachment) && !string.IsNullOrEmpty(attachmentName))
                {
                    string[] attachmentArray     = attachment.Trim(';').Split(';');
                    string[] attachmentNameArray = attachmentName.Trim(';').Split(';');

                    if (attachmentArray.Length == attachmentNameArray.Length)
                    {
                        for (int cnt = 0; cnt <= attachmentArray.Length - 1; cnt++)
                        {
                            if (System.IO.File.Exists(attachmentArray[cnt]))
                            {
                                try
                                {
                                    string fileName = ConvertTo.String(attachmentName[cnt]);
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        System.IO.FileStream       fs     = new System.IO.FileStream(attachmentArray[cnt], System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                        System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(fs, fileName);
                                        mailMesg.Attachments.Add(attach);
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }

                if (attachmentByteList != null && attachmentName != null)
                {
                    string[] attachmentNameArray = attachmentName.Trim(';').Split(';');

                    if (attachmentByteList.Count == attachmentNameArray.Length)
                    {
                        for (int cnt = 0; cnt <= attachmentByteList.Count - 1; cnt++)
                        {
                            string fileName = attachmentNameArray[cnt];
                            if (!string.IsNullOrEmpty(fileName))
                            {
                                try
                                {
                                    MemoryStream ms = new MemoryStream(attachmentByteList[cnt]);
                                    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, fileName);
                                    mailMesg.Attachments.Add(attach);
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }

                mailMesg.Subject = subject;
                mailMesg.AlternateViews.Add(GetMasterBody(body, subject, emailType, languageId, sender, mailLogo, LoginUrl));
                mailMesg.IsBodyHtml = true;

                System.Net.Mail.SmtpClient objSMTP = new System.Net.Mail.SmtpClient();
                try
                {
                    objSMTP.Send(mailMesg);
                    return(true);
                }
                catch (Exception ex)
                {
                    LogWritter.WriteErrorFile(ex);
                }
                finally
                {
                    objSMTP.Dispose();
                    mailMesg.Dispose();
                    mailMesg = null;
                }
            }

            return(false);
        }
Exemplo n.º 26
0
 public static bool Send(Models.MailItem o)
 {
     try
     {
         if ((o?.To?.Length ?? 0) < 1)
         {
             return(false);
         }
         using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage()
         {
             From = new System.Net.Mail.MailAddress(o.From),
             Subject = o.Subject,
             Body = o.Body
         })
         {
             foreach (string s in o.To)
             {
                 mail.To.Add(new System.Net.Mail.MailAddress(s));
             }
             if ((o.Cc?.Length ?? 0) > 0)
             {
                 foreach (string s in o.Cc)
                 {
                     mail.CC.Add(new System.Net.Mail.MailAddress(s));
                 }
             }
             if ((o.Bcc?.Length ?? 0) > 0)
             {
                 foreach (string s in o.Bcc)
                 {
                     mail.Bcc.Add(new System.Net.Mail.MailAddress(s));
                 }
             }
             if ((o.AttachmentPath?.Length ?? 0) > 0)
             {
                 foreach (string f in o.AttachmentPath)
                 {
                     if (System.IO.File.Exists(f))
                     {
                         mail.Attachments.Add(new System.Net.Mail.Attachment(f));
                     }
                     else
                     {
                         Logger?.Error("Cannot find attachment {0}", f);
                     }
                 }
             }
             using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient()
             {
                 EnableSsl = true,
                 Port = o.SmtpPort,//587,
                 DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
                 UseDefaultCredentials = false,
                 Credentials = new System.Net.NetworkCredential(o.SmtpUserName, o.SmtpPassword),
                 Host = o.SmtpHost
             })
             {
                 client.Send(mail);
                 client.Dispose();/// Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the SmtpClient class.
                 Logger?.Debug("Send email with subject = {0}", o?.Subject);
                 Logger?.Debug("Recipient = {0}", string.Join(";", o.To));
             }
             mail.Dispose();
         }
         return(true);
     }
     catch (Exception ex)
     {
         Logger?.Error("Subject = {0}", o?.Subject);
         Logger?.Error(ex);
         return(false);
     }
 }
Exemplo n.º 27
0
        private static void sendEmailWithSmtpServer(Configuration.InstallationStandard.SmtpServer smtpServer, EmailMessage message)
        {
            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient();

            try {
                if (smtpServer != null)
                {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host           = smtpServer.Server;
                    if (smtpServer.PortSpecified)
                    {
                        smtpClient.Port = smtpServer.Port;
                    }
                    if (smtpServer.Credentials != null)
                    {
                        smtpClient.Credentials = new System.Net.NetworkCredential(smtpServer.Credentials.UserName, smtpServer.Credentials.Password);
                        smtpClient.EnableSsl   = true;
                    }
                }
                else
                {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;

                    var pickupFolderPath = EwlStatics.CombinePaths(ConfigurationStatics.RedStaplerFolderPath, "Outgoing Dev Mail");
                    Directory.CreateDirectory(pickupFolderPath);
                    smtpClient.PickupDirectoryLocation = pickupFolderPath;
                }

                using (var m = new System.Net.Mail.MailMessage()) {
                    m.From = message.From.ToMailAddress();
                    addAddressesToMailAddressCollection(message.ReplyToAddresses, m.ReplyToList);

                    addAddressesToMailAddressCollection(message.ToAddresses, m.To);
                    addAddressesToMailAddressCollection(message.CcAddresses, m.CC);
                    addAddressesToMailAddressCollection(message.BccAddresses, m.Bcc);

                    m.Subject = message.Subject;

                    foreach (var i in message.CustomHeaders)
                    {
                        m.Headers.Add(i.Item1, i.Item2);
                    }

                    m.Body = htmlToPlainText(message.BodyHtml);

                    // Add an alternate view for the HTML part.
                    m.AlternateViews.Add(
                        System.Net.Mail.AlternateView.CreateAlternateViewFromString(message.BodyHtml, new System.Net.Mime.ContentType(ContentTypes.Html)));

                    foreach (var attachment in message.Attachments)
                    {
                        m.Attachments.Add(attachment.ToAttachment());
                    }

                    try {
                        smtpClient.Send(m);
                    }
                    catch (System.Net.Mail.SmtpException e) {
                        throw new EmailSendingException("Failed to send an email message using an SMTP server.", e);
                    }
                }
            }
            finally {
                // Microsoft's own dispose method fails to work if Host is not specified, even though Host doesn't need to be specified for operation.
                if (!string.IsNullOrEmpty(smtpClient.Host))
                {
                    smtpClient.Dispose();
                }
            }
        }
Exemplo n.º 28
0
        static void Main(String[] args)
        {
            if (args.Length > 0)
            {
                #region バッチモード

                /********************************************************************************
                * 受け付けるコマンドライン引数の形式                                           *
                *  -r  リビジョン番号                                                         *
                *  -rt コミット日付F:コミット日付T                                            *
                *  -f  対象資産格納フォルダパス                                               *
                *   ※[-r],[-rt],[-f]はいずれかの指定が必須                                    *
                *                                                                              *
                *   -m  メールアドレス                                                         *
                *   ※[-m]を指定すると比較結果を指定アドレスに送信する                         *
                *                                                                              *
                *   -t  比較結果格納パス                                                       *
                ********************************************************************************/

                List <string> lst_str_リビジョン番号 = new List <string>();
                string        str_対象資産格納パス    = string.Empty;
                string        str_メールアドレス     = string.Empty;
                string        str_比較結果格納パス    = string.Empty;
                DateTime      dtm_コミット日付F     = DateTime.MaxValue;
                DateTime      dtm_コミット日付T     = DateTime.MinValue;
                int           int_資産種別        = 0;
                string        str_hr          = "─────────────────────────────";

                #region コマンドライン引数の検証
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "-r":
                        int_資産種別 = CmnCD.int_資産種別.リビジョン;
                        lst_str_リビジョン番号.Add(args[++i]);
                        if (!int.TryParse(args[i], out int int_void))
                        {
                            Console.WriteLine("-r " + args[i] + "の指定が不正です");
                            return;
                        }

                        break;

                    case "-rt":
                        int_資産種別 = CmnCD.int_資産種別.リビジョン;
                        i++;

                        if (args[i].StartsWith("Last"))
                        {
                            // LastNdays指定
                            int int_日数 = Convert.ToInt32(Regex.Replace(args[i], "\\D", ""));
                            dtm_コミット日付T = DateTime.Now;
                            dtm_コミット日付F = DateTime.Now.AddDays((-1) * int_日数);
                        }
                        else
                        {
                            string[] str_rt = args[++i].Split(':');
                            if (str_rt.Length != 2 ||
                                !DateTime.TryParse(str_rt[0].Substring(1, str_rt[0].Length - 2), out dtm_コミット日付F) ||
                                !DateTime.TryParse(str_rt[1].Substring(1, str_rt[1].Length - 2), out dtm_コミット日付T))
                            {
                                Console.WriteLine("-rt " + args[i] + "の指定が不正です");
                            }

                            // コミット日付Tはその日の終わりまでを含むものとする
                            dtm_コミット日付T = dtm_コミット日付T.AddDays(1);
                        }

                        break;

                    case "-f":
                        int_資産種別     = CmnCD.int_資産種別.フォルダ;
                        str_対象資産格納パス = args[++i];
                        break;

                    case "-m":
                        str_メールアドレス = args[++i];
                        break;

                    case "-t":
                        str_比較結果格納パス = args[++i];
                        break;

                    default:
                        Console.WriteLine("コマンドライン引数の指定が不正です。                ");
                        Console.WriteLine("                                                    ");
                        Console.WriteLine("[受け付けるコマンドライン引数の形式]                ");
                        Console.WriteLine(" -r  リビジョン番号                                ");
                        Console.WriteLine(" -rt コミット日付F:コミット日付T                   ");
                        Console.WriteLine(" -f  対象資産格納フォルダパス                      ");
                        Console.WriteLine("  ※[-r],[-rt],[-f]はいずれかの指定が必須           ");
                        Console.WriteLine("                                                    ");
                        Console.WriteLine("  -m  メールアドレス                                ");
                        Console.WriteLine("  ※[-m]を指定すると比較結果を指定アドレスに送信する");
                        Console.WriteLine("                                                    ");
                        Console.WriteLine("  -t  比較結果格納パス                              ");
                        Console.WriteLine("                                                    ");
                        return;
                    }
                }

                if (lst_str_リビジョン番号.Count == 0 &&
                    str_対象資産格納パス == string.Empty &&
                    (dtm_コミット日付F == DateTime.MaxValue && dtm_コミット日付T == DateTime.MinValue))
                {
                    Console.WriteLine("[-r],[-rt],[-f]のいずれかを指定してください");
                    return;
                }

                if (!(lst_str_リビジョン番号.Count > 0
                      ^ str_対象資産格納パス != string.Empty
                      ^ (dtm_コミット日付F != DateTime.MaxValue || dtm_コミット日付T != DateTime.MinValue)))
                {
                    Console.WriteLine("[-r],[-rt],[-f]のいずれか1つのみを指定してください");
                    return;
                }
                #endregion

                List <List <string> > lst_資産一覧  = new List <List <string> >();
                List <string>         ret_資産一覧  = new List <string>();
                Settings1             settings1 = new Settings1();
                string        str_リポジトリパス       = settings1.対象リポジトリroot + settings1.PKGリポジトリfolder;
                List <string> lst_str_output    = new List <string>();
                string        str_output        = string.Empty;


                // コミット日付を指定している場合、期間内のコミット履歴を取得し
                // 対象のリビジョン分、個別資産比較を繰り返し実行する
                List <CmnClass.コミットログ> lst_コミットログ = new List <CmnClass.コミットログ>();
                if (dtm_コミット日付F != DateTime.MaxValue && dtm_コミット日付T != DateTime.MinValue)
                {
                    CmnModule.ModGetコミットログ(str_リポジトリパス, dtm_コミット日付F, dtm_コミット日付T, out lst_コミットログ);
                    lst_コミットログ.ForEach(obj => lst_str_リビジョン番号.Add(obj.Int_リビジョン番号.ToString()));
                }

                // 対象資産一覧を取得
                switch (int_資産種別)
                {
                case CmnCD.int_資産種別.フォルダ:

                    CmnModule.ModGet資産一覧fromフォルダパス(str_対象資産格納パス, out ret_資産一覧);
                    lst_資産一覧.Add(ret_資産一覧);

                    #region EDT:実行結果
                    str_output  = string.Empty;
                    str_output += str_hr + Environment.NewLine;
                    str_output += str_対象資産格納パス + "に含まれる対象資産" + Environment.NewLine;
                    ret_資産一覧.ForEach(s => str_output += " □" + Regex.Replace(s, ".*\\\\", "") + Environment.NewLine);
                    str_output += str_hr + Environment.NewLine;

                    lst_str_output.Add(str_output);
                    #endregion
                    break;

                case CmnCD.int_資産種別.リビジョン:

                    foreach (string str_リビジョン番号 in lst_str_リビジョン番号)
                    {
                        CmnModule.ModGet資産一覧fromリポジトリパス(str_リポジトリパス, str_リビジョン番号, out ret_資産一覧);
                        lst_資産一覧.Add(ret_資産一覧);

                        #region EDT:実行結果
                        str_output  = string.Empty;
                        str_output += str_hr + Environment.NewLine;

                        CmnClass.コミットログ obj_コミットログ = lst_コミットログ.Find(obj => obj.Int_リビジョン番号.ToString() == str_リビジョン番号);
                        if (obj_コミットログ != null)
                        {
                            str_output += "r" + str_リビジョン番号;
                            str_output += " comitted by " + obj_コミットログ.Str_ユーザー + Environment.NewLine;
                            str_output += obj_コミットログ.Str_コメント;
                            str_output += Environment.NewLine;
                        }
                        else
                        {
                            str_output += "r" + str_リビジョン番号;
                            str_output += "に含まれる対象資産" + Environment.NewLine;
                        }

                        ret_資産一覧.ForEach(s => str_output += " □" + Regex.Replace(s, ".*\\\\", "") + Environment.NewLine);
                        str_output += str_hr + Environment.NewLine;
                        lst_str_output.Add(str_output);
                        #endregion
                    }
                    break;

                default:
                    return;
                }

                // リポジトリごとの個別資産一覧を取得→比較する
                string[] ary_str_対象リポジトリfolder = settings1.対象リポジトリfolder.Split(',');
                foreach (string str_対象リポジトリfolder in ary_str_対象リポジトリfolder)
                {
                    str_リポジトリパス = settings1.対象リポジトリroot + str_対象リポジトリfolder;
                    List <string> lst_個別資産一覧;
                    List <string> lst_result;

                    CmnModule.ModGet資産一覧fromリポジトリパス(str_リポジトリパス, out lst_個別資産一覧);

                    for (int i = 0; i < lst_資産一覧.Count; i++)
                    {
                        CmnModule.ModCompare資産一覧(lst_資産一覧[i], lst_個別資産一覧, out lst_result);

                        #region EDT:実行結果
                        str_output  = string.Empty;
                        str_output += str_対象リポジトリfolder + "上の個別資産" + Environment.NewLine;

                        if (lst_result.Count > 0)
                        {
                            lst_result.ForEach(s => str_output += " □" + s + Environment.NewLine);
                        }
                        else
                        {
                            str_output += " ■個別資産なし" + Environment.NewLine;
                        }

                        lst_str_output[i] += Environment.NewLine + str_output + Environment.NewLine;
                        #endregion
                    }
                }

                #region OUT:実行結果
                // とりあえず標準出力
                lst_str_output.ForEach(s => Console.WriteLine(s));

                // 比較結果格納パス[-t]が指定されている場合、ファイル保存する
                if (str_比較結果格納パス != string.Empty)
                {
                    StreamWriter obj_StreamWriter = new StreamWriter(
                        str_比較結果格納パス + "\\資産比較結果" + DateTime.Now.ToString("_yyyyMMdd") + ".log",
                        false,
                        Encoding.GetEncoding("shift-jis"));

                    str_output = string.Empty;
                    lst_str_output.ForEach(s => str_output += s);
                    obj_StreamWriter.Write(str_output);
                    obj_StreamWriter.Close();
                }

                // メールアドレス[-m]が指定されている場合、メール送信する
                if (str_メールアドレス != string.Empty)
                {
                    string str_送信メールアドレス = "*****@*****.**";
                    string str_宛先メールアドレス = str_メールアドレス;
                    string str_件名        = "[" + DateTime.Now.ToShortDateString() + "] 個別資産確認ログ (自動送信メール)";
                    string str_内容        = string.Empty;

                    // 内容編集:ヘッダ部分
                    str_内容 = "個別資産確認ツール実行条件" + Environment.NewLine;
                    if (dtm_コミット日付F != DateTime.MaxValue)
                    {
                        str_内容 += "・対象期間(F):" + dtm_コミット日付F.ToShortDateString() + Environment.NewLine;
                    }
                    if (dtm_コミット日付T != DateTime.MinValue)
                    {
                        str_内容 += "・対象期間(T):" + dtm_コミット日付T.AddDays(-1).ToShortDateString() + Environment.NewLine;
                    }
                    str_内容 += "・対象リビジョン番号:" + string.Join(", ", lst_str_リビジョン番号.ToArray()) + Environment.NewLine;
                    str_内容 += Environment.NewLine;

                    // 内容編集:比較結果部分
                    lst_str_output.ForEach(s => str_内容 += s + Environment.NewLine);

                    System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient()
                    {
                        Host           = settings1.SMTPサーバ,
                        Port           = Convert.ToInt32(settings1.SMTPポート番号),
                        DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
                    };

                    sc.Send(str_送信メールアドレス, str_宛先メールアドレス, str_件名, str_内容);
                    sc.Dispose();
                }
                #endregion

                #endregion
            }
            else
            {
                // Windowsモード
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
Exemplo n.º 29
0
        public static bool SendForWindowService(string mailFrom, string mailTo, string mailCC, string mailBCC, string subject, string body, string path)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (!string.IsNullOrEmpty(mailTo))
            {
                mailTo = mailTo.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailCC))
            {
                mailCC = mailCC.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailBCC))
            {
                mailBCC = mailBCC.Trim(';').Trim(',');
            }

            if (ValidateEmail(mailFrom, mailTo) && (string.IsNullOrEmpty(mailCC) || ValidateEmail(mailCC)) && (string.IsNullOrEmpty(mailBCC) || ValidateEmail(mailBCC)))
            {
                System.Net.Mail.MailMessage mailMesg = new System.Net.Mail.MailMessage();
                mailMesg.From = new System.Net.Mail.MailAddress(mailFrom);
                if (!string.IsNullOrEmpty(mailTo))
                {
                    mailTo = mailTo.Replace(";", ",");
                    mailMesg.To.Add(mailTo);
                }

                if (!string.IsNullOrEmpty(mailCC))
                {
                    mailCC = mailCC.Replace(";", ",");
                    mailMesg.CC.Add(mailCC);
                }

                if (!string.IsNullOrEmpty(mailBCC))
                {
                    mailBCC = mailBCC.Replace(";", ",");
                    mailMesg.Bcc.Add(mailBCC);
                }

                mailMesg.Subject = subject;

                mailMesg.AlternateViews.Add(GetMasterBodyForWindowService(body, subject, path));
                mailMesg.IsBodyHtml = true;

                System.Net.Mail.SmtpClient objSMTP = new System.Net.Mail.SmtpClient();
                try
                {
                    objSMTP.Send(mailMesg);
                    return(true);
                }
                catch (Exception ex)
                {
                    LogWritter.WriteErrorFile(ex);
                }
                finally
                {
                    objSMTP.Dispose();
                    mailMesg.Dispose();
                    mailMesg = null;
                }
            }

            return(false);
        }
Exemplo n.º 30
0
        public ActionResult <Confirm> Send([FromBody] Confirm param)
        {
            if (param == null)
            {
                param          = new Confirm();
                param._message = _localizer["No parameters."];
                return(BadRequest(param));
            }

            try
            {
                var sc = new System.Net.Mail.SmtpClient
                {
                    //SMTPサーバーを指定する
                    //Host = "pop3.lolipop.jp", // or "mailgate.ipentec.com";
                    Host = "smtp8.gmoserver.jp",
                    Port = 587,   // or 587;
                                  //string smtpserver = "pop3.lolipop.jp";
                                  //int port = 587;

                    //ユーザー名とパスワードを設定する
                    //Credentials = new System.Net.NetworkCredential(vmodel.FromEmail, "Tomoko3104_321"),
                    Credentials = new System.Net.NetworkCredential(param.FromEmail, "ewgya$0k"),
                    //Properties.Settings.Default.SMTPAuthUser, Properties.Settings.Default.SMTPAuthPass);
                    //or sc.Credentials = new System.Net.NetworkCredential("automail","pass123456");
                    DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,

                    //現在は、EnableSslがtrueでは失敗する
                    EnableSsl = true
                };
                var okCount = 0;
                var ngCount = 0;
                foreach (var i in param.SelectedList)
                {
                    if (i.IsSelect)
                    {
                        //var enc = Encoding.GetEncoding(65001);
                        //var enc_2022 = Encoding.GetEncoding(50220);
                        //var from = myEncode(vmodel.FromEmail, enc_2022);
                        //var subject = myEncode(vmodel.Subject, enc_2022);
                        var msg = new System.Net.Mail.MailMessage();
                        msg.From = new System.Net.Mail.MailAddress(param.FromEmail, param.Sender);
                        msg.To.Add(new System.Net.Mail.MailAddress(i.ToEmail, i.TuserName));
                        if (i.ToEmail2 != null && i.ToEmail2 != "")
                        {
                            msg.To.Add(new System.Net.Mail.MailAddress(i.ToEmail2, i.TuserName));
                        }
                        if (i.ToEmail3 != null && i.ToEmail3 != "")
                        {
                            msg.To.Add(new System.Net.Mail.MailAddress(i.ToEmail3, i.TuserName));
                        }
                        msg.IsBodyHtml = false;
                        msg.Subject    = param.Subject;
                        msg.Body       = BuildBodyStr(param, i);

                        try
                        {
                            //メッセージを送信する
                            sc.Send(msg);
                            i.SentDate     = DateTime.Now.ToLongDateString();
                            i.Status       = "OK";
                            i.IsError      = "false";
                            i.IsSent       = "true";
                            i.ErrorMessage = null;
                            okCount       += 1;

                            //後始末
                            msg.Dispose();
                        }
                        catch (Exception ex)
                        {
                            i.SentDate     = DateTime.Now.ToLongDateString();
                            i.Status       = "NG";
                            i.IsError      = "true";
                            i.IsSent       = "false";
                            i.ErrorMessage = ex.Message;
                            ngCount       += 1;

                            //後始末
                            msg.Dispose();
                        }

                        //1件づつ登録
                        //更新前データを取得する
                        var storeModel = (from a in _context.MailTusers
                                          where a.MailId.Equals(i.MailId)
                                          where a.TuserId.Equals(i.TuserId)
                                          select a).FirstOrDefault();

                        if (storeModel == null)
                        {
                            param._message = _localizer["It has already been deleted."];
                            return(BadRequest(param));
                        }

                        ReflectionUtility.Model2Model(param, storeModel);
                        storeModel.Updated  = DateTime.Now;
                        storeModel.Version += 1;


                        _context.MailTusers.Update(storeModel);
                        _context.SaveChanges();
                    }
                }
                _context.SaveChanges();

                sc.Dispose();

                //メール登録
                var mail = new Mail();
                ReflectionUtility.Model2Model(param, mail);


                try
                {
                    mail.IsSent     = true;
                    mail.IsDraft    = false;
                    mail.ErrorCount = ngCount;
                    mail.SentCount  = okCount;
                    mail.Updated    = DateTime.Now;
                    mail.Registed   = DateTime.Now;
                    mail.Version    = 1;
                    _context.Mails.Update(mail);
                    _context.SaveChanges();

                    ReflectionUtility.Model2Model(mail, param);


                    return(Ok(param));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    param._message = _localizer["System error Please inform system personnel.({0})", ex.Message];
                    return(BadRequest(param));
                }
            }
            catch (Exception ex)
            {
                param._message = _localizer["System error Please inform system personnel.({0})", ex.Message];
                return(BadRequest(param));
            }
        }
Exemplo n.º 31
0
 public void Dispose()
 {
     _smtpClient.Dispose();
 }
Exemplo n.º 32
0
    public void RunMarimo() {

      //string[] codelist = { "while,true", "wait,0.5", "f_temp,get,temp", "send,f_temp", "if,f_temp,<,40", "break", "endi,4", "endw,0", "send,Worning!" };
      //string[] codelist = {"f_distance,0","f_before,get,temp","while,true","wait,1","f_after,get,temp","f_distance,f_after,-,f_before","send,f_distance","f_before,f_after","endw,2"};
      //string[] codelist = { "i_i,0", "i_j,0", "while,count,6", "while,count,4", "send,i_j", "send,i_i", "i_i,i_i,+,1", "endw,3", "i_i,0", "i_j,i_j,+,1", "endw,2" };

      val_int = new List<val_ints>();
      val_float = new List<val_floats>();
      List<bool> WhileCountStart = new List<bool>();
      List<int> WhileCount = new List<int>();

      for (int i = 0; i < codelist.Length; i++) {
        WhileCountStart.Add(false);
        WhileCount.Add(0);
      }

      string[] rowlist;
      float[] calite = new float[2];
      bool Flag_clause = false;

      int row = 0;
      int row_tmp = 0;

      while (true) {

        if (row == codelist.Length) {
          break;
        }

        rowlist = codelist[row].Split(',');

        if (rowlist[0].IndexOf('_') > -1) {

          // 変数代入("i_abc,5"or"i_abc,i_def")
          if (rowlist.Length == 2) {
            if (rowlist[0].Split('_')[0].Equals("i")) {
              if (val_int.Count != getadr_i(rowlist[0])) {
                val_int.RemoveAt(getadr_i(rowlist[0]));
              }
              if (rowlist[1].IndexOf('_') > 0) {
                val_int.Add(new val_ints { Name = rowlist[0].Split('_')[1], Val = val_int[getadr_i(rowlist[1])].Val });
              } else {
                val_int.Add(new val_ints { Name = rowlist[0].Split('_')[1], Val = int.Parse(rowlist[1]) });
              }
            } else if (rowlist[0].Split('_')[0].Equals("f")) {
              if (val_float.Count != getadr_f(rowlist[0])) {
                val_float.RemoveAt(getadr_f(rowlist[0]));
              }
              if (rowlist[1].IndexOf('_') > 0) {
                val_float.Add(new val_floats { Name = rowlist[0].Split('_')[1], Val = val_float[getadr_i(rowlist[1])].Val });
              } else {
                val_float.Add(new val_floats { Name = rowlist[0].Split('_')[1], Val = float.Parse(rowlist[1]) });
              }
            }
          }

          // CPU温度取得("i_temp,get,temp")
          if (rowlist.Length == 3) {
            if (rowlist[2].Equals("temp")) {
              if (rowlist[0].Split('_')[0].Equals("i")) {
                if (val_int.Count != getadr_i(rowlist[0])) {
                  val_int.RemoveAt(getadr_i(rowlist[0]));
                }
                val_int.Add(new val_ints { Name = rowlist[0].Split('_')[1], Val = int.Parse(getTemp()) });
              } else if (rowlist[0].Split('_')[0].Equals("f")) {
                if (val_float.Count != getadr_f(rowlist[0])) {
                  val_float.RemoveAt(getadr_f(rowlist[0]));
                }
                val_float.Add(new val_floats { Name = rowlist[0].Split('_')[1], Val = float.Parse(getTemp()) });
              }
            }
          }

          // GPIO取得orデータの取得
          if (rowlist.Length == 4) {

            // GPIOの値取得("i_gpio,get,gpio,3")
            if (rowlist[2].Equals("gpio")) {
              if (rowlist[0].Split('_')[0].Equals("i")) {
                if (val_int.Count != getadr_i(rowlist[0])) {
                  val_int.RemoveAt(getadr_i(rowlist[0]));
                }
                val_int.Add(new val_ints { Name = rowlist[0].Split('_')[1], Val = int.Parse(getGPIO(int.Parse(rowlist[3]))) });
              } else if (rowlist[0].Split('_')[0].Equals("f")) {
                if (val_float.Count != getadr_f(rowlist[0])) {
                  val_float.RemoveAt(getadr_f(rowlist[0]));
                }
                val_float.Add(new val_floats { Name = rowlist[0].Split('_')[1], Val = float.Parse(getGPIO(int.Parse(rowlist[3]))) });
              }
            }

            // データの取得 ("i_data1,get,nowdata,2")
            else if (rowlist[2].Equals("nowdata")) {
              if (rowlist[0].Split('_')[0].Equals("i")) {
                if (val_int.Count != getadr_i(rowlist[0])) {
                  val_int.RemoveAt(getadr_i(rowlist[0]));
                }
                val_int.Add(new val_ints { Name = rowlist[0].Split('_')[1], Val = int.Parse(dataadd.dat[int.Parse(rowlist[3]) - 1]) });
              }
              if (rowlist[0].Split('_')[0].Equals("f")) {
                if (val_float.Count != getadr_f(rowlist[0])) {
                  val_float.RemoveAt(getadr_f(rowlist[0]));
                }
                val_float.Add(new val_floats { Name = rowlist[0].Split('_')[1], Val = float.Parse(dataadd.dat[int.Parse(rowlist[3]) - 1]) });
              }
            }

          // 2項演算("i_result,i_x1,+,5")
            else {
              if (rowlist[0].Split('_')[0].Equals("i")) {
                calite = calite_i(rowlist);
                if (rowlist[2].Equals("+")) {
                  val_int[getadr_i(rowlist[0])].Val = (int)calite[0] + (int)calite[1];
                }
                if (rowlist[2].Equals("-")) {
                  val_int[getadr_i(rowlist[0])].Val = (int)calite[0] - (int)calite[1];
                }
                if (rowlist[2].Equals("*")) {
                  val_int[getadr_i(rowlist[0])].Val = (int)calite[0] * (int)calite[1];
                }
                if (rowlist[2].Equals("/")) {
                  val_int[getadr_i(rowlist[0])].Val = (int)calite[0] / (int)calite[1];
                }
                if (rowlist[2].Equals("%")) {
                  val_int[getadr_i(rowlist[0])].Val = (int)calite[0] % (int)calite[1];
                }
              }
              if (rowlist[0].Split('_')[0].Equals("f")) {
                calite = calite_f(rowlist);
                if (rowlist[2].Equals("+")) {
                  val_float[getadr_i(rowlist[0])].Val = calite[0] + calite[1];
                }
                if (rowlist[2].Equals("-")) {
                  val_float[getadr_i(rowlist[0])].Val = calite[0] - calite[1];
                }
                if (rowlist[2].Equals("*")) {
                  val_float[getadr_i(rowlist[0])].Val = calite[0] * calite[1];
                }
                if (rowlist[2].Equals("/")) {
                  val_float[getadr_i(rowlist[0])].Val = calite[0] / calite[1];
                }
                if (rowlist[2].Equals("%")) {
                  val_float[getadr_i(rowlist[0])].Val = calite[0] % calite[1];
                }
              }
            }

            row++;
          }

          // if文("if,i_x1,>,i_x2"~"elif,i_x1,>i_x3"~"else,3"~"endi,3")
        } else if (rowlist[0].Equals("if")) {

          Flag_clause = relation(rowlist);

          if (Flag_clause) {
            row_tmp = row;
            while (true) {
              row++;
              if (codelist[row].Split(',')[0].Equals("else") || codelist[row].Split(',')[0].Equals("endi")) {
                if (codelist[row].Split(',')[1].Equals(row_tmp.ToString())) {
                  row++;
                  break;
                }
              }
              if (codelist[row].Split(',')[0].Equals("elif")) {
                if (codelist[row].Split(',')[4].Equals(row_tmp.ToString())) {
                  bool Flag_elif = true;
                  while (Flag_elif) {
                    rowlist = codelist[row].Split(',');
                    Flag_clause = relation(rowlist);
                    if (Flag_clause) {
                      while (true) {
                        row++;
                        if (codelist[row].Split(',')[0].Equals("else") || codelist[row].Split(',')[0].Equals("endi")) {
                          if (codelist[row].Split(',')[1].Equals(row_tmp.ToString())) {
                            row++;
                            Flag_elif = false;
                            break;
                          }
                        }
                        if (codelist[row].Split(',')[0].Equals("elif")) {
                          if (codelist[row].Split(',')[4].Equals(row_tmp.ToString())) {
                            break;
                          }
                        }
                      }
                    } else {
                      row++;
                      break;
                    }
                  }
                  break;
                }
              }
            }
          } else {
            row++;
          }


          // while文
        } else if (rowlist[0].Equals("while")) {

          // 無限ループ("while,true"~"endw,2")
          if (rowlist[1].Equals("true")) {
            row++;
          }

          // 回数ループ("while,count,5"~"endw,2")
          if (rowlist[1].Equals("count")) {
            if (WhileCountStart[row]) {
              if (WhileCount[row] == (int.Parse(rowlist[2]) - 1)) {
                WhileCountStart[row] = false;
                row_tmp = row;
                while (true) {
                  row++;
                  if (codelist[row].Split(',')[0].Equals("endw")) {
                    if (codelist[row].Split(',')[1].Equals(row_tmp.ToString())) {
                      row++;
                      break;
                    }
                  }
                }
              } else {
                WhileCount[row]++;
                row++;
              }
            } else {
              WhileCountStart[row] = true;
              WhileCount[row] = 0;
              row++;
            }
          }

          // 条件ループ("while,i_x1,<,100"~"endw,2")
          if (rowlist.Length == 4) {
            Flag_clause = relation(rowlist);
            if (Flag_clause) {
              row_tmp = row;
              while (true) {
                row++;
                if (codelist[row].Split(',')[0].Equals("endw")) {
                  if (codelist[row].Split(',')[1].Equals(row_tmp.ToString())) {
                    row++;
                    break;
                  }
                }
              }
            } else {
              row++;
            }
          }


          // wait文("wait,1000")
        } else if (rowlist[0].Equals("wait")) {

          Thread.Sleep(int.Parse(rowlist[1]));
          row++;


          // add文(データの追加)
        }else if (rowlist[0].Equals("add")){

          if (dataadd.dat.Count < int.Parse(rowlist[1])) {
            int Count = int.Parse(rowlist[1]) - dataadd.dat.Count;
            for (int i = 0; i < Count; i++) {
              dataadd.dat.Add("");
              Debug.WriteLine("Count: " + dataadd.dat.Count);
            }
          }

            // 追加データが変数 ("add,4,i_data1")
          if (rowlist[2].IndexOf('_') > -1) {

            if (rowlist[2].Split('_')[0].Equals("i")) {
              dataadd.dat[int.Parse(rowlist[1]) - 1] = val_int[getadr_i(rowlist[1])].Val.ToString();
            }
            if (rowlist[2].Split('_')[0].Equals("f")) {
              dataadd.dat[int.Parse(rowlist[1]) - 1] = val_float[getadr_f(rowlist[1])].Val.ToString();
            }

            // 追加データが自由 ("add,5,56.7" "add,6,Worning!!")
          } else {

            dataadd.dat[int.Parse(rowlist[1]) - 1] = rowlist[2];

          }

          row++;

          // send文
        } else if (rowlist[0].Equals("send")) {

          // 変数 ("send,i_x1" or "send,hogehoge")
          if (rowlist.Length == 2) {
            if (rowlist[1].IndexOf('_') > 0) {
              if (rowlist[1].Split('_')[0].Equals("i")) {
                Debug.WriteLine("send: " + val_int[getadr_i(rowlist[1])].Val.ToString());
              }
              if (rowlist[1].Split('_')[0].Equals("f")) {
                Debug.WriteLine("send: " + val_float[getadr_f(rowlist[1])].Val.ToString());
              }
            } else {
              Debug.WriteLine("send: " + rowlist[1]);
            }

            // CPU温度 ("send,get,temp")
          } else if (rowlist.Length == 3) {
            Debug.WriteLine("send: " + getTemp());

            // GPIO値 ("send,get,gpio,1")
          } else if (rowlist.Length == 4) {
            Debug.WriteLine("send: " + getGPIO(int.Parse(rowlist[3])));
          }

          row++;
        
          // mail送信("mail,[email protected],件名,本文")
        } else if (rowlist[0].Equals("mail")) {

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(
               "*****@*****.**", rowlist[1],
               rowlist[2], rowlist[3]);
            System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
            sc.Host = "smtp.gmail.com";
            sc.Port = 587;
            sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            sc.Credentials = new System.Net.NetworkCredential("*****@*****.**", "MarimoCats");
            sc.EnableSsl = true;
            sc.Send(msg);
            msg.Dispose();
            sc.Dispose();
            row++;

          // break文("break")
        } else if (rowlist[0].Equals("break")) {

          while (true) {
            row++;
            if (codelist[row].Split(',')[0].Equals("endw")) {
              row++;
              break;
            }
          }


          // continue文("continue")
        } else if (rowlist[0].Equals("continue")) {

          while (true) {
            row++;
            if (codelist[row].Split(',')[0].Equals("endw")) {
              row = int.Parse(codelist[row].Split(',')[1]);
              break;
            }
          }


          // if文に入った場合のelse
        } else if (rowlist[0].Equals("else")) {

          while (true) {
            row++;
            if (codelist[row].Split(',')[0].Equals("endi")) {
              if (codelist[row].Split(',')[1].Equals(rowlist[1])) {
                row++;
                break;
              }
            }
          }


          // if文に入った場合のelif
        } else if (rowlist[0].Equals("elif")) {

          while (true) {
            row++;
            if (codelist[row].Split(',')[0].Equals("endi")) {
              if (codelist[row].Split(',')[1].Equals(rowlist[4])) {
                row++;
                break;
              }
            }
          }


          // while文に入った場合のendw
        } else if (rowlist[0].Equals("endw")) {

          row = int.Parse(rowlist[1]);


          // if文に入った場合のendi
        } else if (rowlist[0].Equals("endi")) {

          row++;


          // 例外はスルー
        } else {

          row++;

        }



      }
    
    }
Exemplo n.º 33
0
 public static void SendEmailNotification(List<System.Net.Mail.MailMessage> emails)
 {
     if (!Lib.Utility.Common.IsNullOrEmptyList(emails))
     {
         System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["smtphost"]);
         try
         {
             foreach (System.Net.Mail.MailMessage obj_message in emails)
             {
                 smtp.Send(obj_message);
             }
             smtp.Dispose();
         }
         catch (Exception exc)
         {
             throw exc;
         }
         finally
         {
             smtp.Dispose();
         }
     }
 }
Exemplo n.º 34
0
 /// <summary>
 /// 邮件的发送;发送成功返回null,失败返回失败原因
 /// </summary>
 /// <returns>发送失败则返回错误信息</returns>
 public string Send()
 {
     mSmtpClient = new System.Net.Mail.SmtpClient();
     try
     {
         if (mMailMessage != null)
         {
             //mSmtpClient.Host = "smtp." + mMailMessage.From.Host;
             mSmtpClient.Host = this.mSenderServerHost;
             mSmtpClient.Port = this.mSenderPort;
             mSmtpClient.UseDefaultCredentials = false;
             mSmtpClient.EnableSsl = this.mEnableSsl;
             if (this.mEnablePwdAuthentication)
             {
                 System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                 //mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                 //NTLM: Secure Password Authentication in Microsoft Outlook Express
                 mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
             }
             else
             {
                 mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
             }
             mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
             mSmtpClient.Send(mMailMessage);
         }
     }
     catch(Exception ex)
     {
         return ex.Message;
     }
     finally
     {
         mSmtpClient.Dispose();
     }
     return null;
 }
Exemplo n.º 35
0
 public override void Dispose()
 {
     client.Dispose();
 }
        private static void sendEmailWithSendGrid( SendGrid sendGrid, EmailMessage message )
        {
            // We want this method to use the SendGrid API (https://github.com/sendgrid/sendgrid-csharp), but as of 20 June 2014 it looks like the SendGrid Web API
            // does not support CC recipients!

            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient( "smtp.sendgrid.net", 587 );
            try {
                smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtpClient.Credentials = new System.Net.NetworkCredential( sendGrid.UserName, sendGrid.Password );

                using( var m = new System.Net.Mail.MailMessage() ) {
                    message.ConfigureMailMessage( m );
                    try {
                        smtpClient.Send( m );
                    }
                    catch( System.Net.Mail.SmtpException e ) {
                        throw new EmailSendingException( "Failed to send an email message using SendGrid.", e );
                    }
                }
            }
            finally {
                smtpClient.Dispose();
            }
        }
        static void SendMail(string subject, string text, string destination) {
            Console.WriteLine("SendMail_Start");

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(
               "*****@*****.**", destination,
               subject, text);
            System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
            sc.Host = "smtp.gmail.com";
            sc.Port = 587;
            sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            sc.Credentials = new System.Net.NetworkCredential("*****@*****.**", "MarimoCats");
            sc.EnableSsl = true;
            sc.Send(msg);
            msg.Dispose();
            sc.Dispose();

            Console.WriteLine("SendMail_End");
        }
        private static void sendEmailWithSmtpServer( SmtpServer smtpServer, EmailMessage message )
        {
            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient();
            try {
                if( smtpServer != null ) {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host = smtpServer.Server;
                    if( smtpServer.PortSpecified )
                        smtpClient.Port = smtpServer.Port;
                    if( smtpServer.Credentials != null ) {
                        smtpClient.Credentials = new System.Net.NetworkCredential( smtpServer.Credentials.UserName, smtpServer.Credentials.Password );
                        smtpClient.EnableSsl = true;
                    }
                }
                else {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;

                    var pickupFolderPath = EwlStatics.CombinePaths( ConfigurationStatics.RedStaplerFolderPath, "Outgoing Dev Mail" );
                    Directory.CreateDirectory( pickupFolderPath );
                    smtpClient.PickupDirectoryLocation = pickupFolderPath;
                }

                using( var m = new System.Net.Mail.MailMessage() ) {
                    message.ConfigureMailMessage( m );
                    try {
                        smtpClient.Send( m );
                    }
                    catch( System.Net.Mail.SmtpException e ) {
                        throw new EmailSendingException( "Failed to send an email message using an SMTP server.", e );
                    }
                }
            }
            finally {
                // Microsoft's own dispose method fails to work if Host is not specified, even though Host doesn't need to be specified for operation.
                if( !string.IsNullOrEmpty( smtpClient.Host ) )
                    smtpClient.Dispose();
            }
        }
Exemplo n.º 39
0
        private static string SendMail(bool SendAsync, string DefaultConnection, string MailFrom, string MailTo, string MailToDisplayName, string Cc, string Bcc, string ReplyTo, string Header, System.Net.Mail.MailPriority Priority,
                                       string Subject, Encoding BodyEncoding, string Body, string[] Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword, bool SMTPEnableSSL)
        {
            string          strSendMail     = "";
            GeneralSettings GeneralSettings = new GeneralSettings(DefaultConnection);

            // SMTP server configuration
            if (SMTPServer == "")
            {
                SMTPServer = GeneralSettings.SMTPServer;

                if (SMTPServer.Trim().Length == 0)
                {
                    return("Error: Cannot send email - SMTPServer not set");
                }
            }

            if (SMTPAuthentication == "")
            {
                SMTPAuthentication = GeneralSettings.SMTPAuthendication;
            }

            if (SMTPUsername == "")
            {
                SMTPUsername = GeneralSettings.SMTPUserName;
            }

            if (SMTPPassword == "")
            {
                SMTPPassword = GeneralSettings.SMTPPassword;
            }

            MailTo = MailTo.Replace(";", ",");
            Cc     = Cc.Replace(";", ",");
            Bcc    = Bcc.Replace(";", ",");

            System.Net.Mail.MailMessage objMail = null;
            try
            {
                System.Net.Mail.MailAddress SenderMailAddress    = new System.Net.Mail.MailAddress(MailFrom, MailFrom);
                System.Net.Mail.MailAddress RecipientMailAddress = new System.Net.Mail.MailAddress(MailTo, MailToDisplayName);

                objMail = new System.Net.Mail.MailMessage(SenderMailAddress, RecipientMailAddress);

                if (Cc != "")
                {
                    objMail.CC.Add(Cc);
                }
                if (Bcc != "")
                {
                    objMail.Bcc.Add(Bcc);
                }

                if (ReplyTo != string.Empty)
                {
                    objMail.ReplyToList.Add(new System.Net.Mail.MailAddress(ReplyTo));
                }

                objMail.Priority   = (System.Net.Mail.MailPriority)Priority;
                objMail.IsBodyHtml = IsHTMLMail(Body);
                objMail.Headers.Add("In-Reply-To", $"ADefHelpDesk-{Header}");

                foreach (string myAtt in Attachment)
                {
                    if (myAtt != "")
                    {
                        objMail.Attachments.Add(new System.Net.Mail.Attachment(myAtt));
                    }
                }

                // message
                objMail.SubjectEncoding = BodyEncoding;
                objMail.Subject         = Subject.Trim();
                objMail.BodyEncoding    = BodyEncoding;

                System.Net.Mail.AlternateView PlainView =
                    System.Net.Mail.AlternateView.CreateAlternateViewFromString(Utility.ConvertToText(Body),
                                                                                null, "text/plain");

                objMail.AlternateViews.Add(PlainView);

                //if body contains html, add html part
                if (IsHTMLMail(Body))
                {
                    System.Net.Mail.AlternateView HTMLView =
                        System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

                    objMail.AlternateViews.Add(HTMLView);
                }
            }

            catch (Exception objException)
            {
                // Problem creating Mail Object
                strSendMail = MailTo + ": " + objException.Message;

                // Log Error to the System Log
                Log.InsertSystemLog(DefaultConnection, Constants.EmailError, "", strSendMail);
            }

            if (objMail != null)
            {
                // external SMTP server alternate port
                int?SmtpPort = null;
                int portPos  = SMTPServer.IndexOf(":");
                if (portPos > -1)
                {
                    SmtpPort   = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
                    SMTPServer = SMTPServer.Substring(0, portPos);
                }

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

                if (SMTPServer != "")
                {
                    smtpClient.Host = SMTPServer;
                    smtpClient.Port = (SmtpPort == null) ? (int)25 : (Convert.ToInt32(SmtpPort));

                    switch (SMTPAuthentication)
                    {
                    case "":
                    case "0":
                        // anonymous
                        break;

                    case "1":
                        // basic
                        if (SMTPUsername != "" & SMTPPassword != "")
                        {
                            smtpClient.UseDefaultCredentials = false;
                            smtpClient.Credentials           = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
                        }

                        break;

                    case "2":
                        // NTLM
                        smtpClient.UseDefaultCredentials = true;
                        break;
                    }
                }
                smtpClient.EnableSsl = SMTPEnableSSL;

                try
                {
                    if (SendAsync) // Send Email using SendAsync
                    {
                        // Set the method that is called back when the send operation ends.
                        smtpClient.SendCompleted += SmtpClient_SendCompleted;

                        // Send the email
                        DTOMailMessage objDTOMailMessage = new DTOMailMessage();
                        objDTOMailMessage.DefaultConnection = DefaultConnection;
                        objDTOMailMessage.MailMessage       = objMail;

                        smtpClient.SendAsync(objMail, objDTOMailMessage);
                        strSendMail = "";
                    }
                    else // Send email and wait for response
                    {
                        smtpClient.Send(objMail);
                        strSendMail = "";

                        // Log the Email
                        LogEmail(DefaultConnection, objMail);

                        objMail.Dispose();
                        smtpClient.Dispose();
                    }
                }
                catch (Exception objException)
                {
                    // mail configuration problem
                    if (!(objException.InnerException == null))
                    {
                        strSendMail = string.Concat(objException.Message, Environment.NewLine, objException.InnerException.Message);
                    }
                    else
                    {
                        strSendMail = objException.Message;
                    }

                    // Log Error to the System Log
                    Log.InsertSystemLog(DefaultConnection, Constants.EmailError, "", strSendMail);
                }
            }

            return(strSendMail);
        }
Exemplo n.º 40
0
        public void UseGmail()
        {
            //建立 SmtpClient 物件 並設定 Gmail的smtp主機及Port
            System.Net.Mail.SmtpClient MySmtp = new System.Net.Mail.SmtpClient("smtp.mail.yahoo.com", 587);

            //設定你的帳號密碼
            MySmtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "dbsmjyuxuycokkat");

            //Gmial 的 smtp 必需要使用 SSL
            MySmtp.EnableSsl = true;

            //發送Email
            MySmtp.Send("*****@*****.**", "*****@*****.**", "Gmail發信測試", "發信測試"); MySmtp.Dispose();
        }
        private static void sendEmailWithSmtpServer( Configuration.InstallationStandard.SmtpServer smtpServer, EmailMessage message )
        {
            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient();
            try {
                if( smtpServer != null ) {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host = smtpServer.Server;
                    if( smtpServer.PortSpecified )
                        smtpClient.Port = smtpServer.Port;
                    if( smtpServer.Credentials != null ) {
                        smtpClient.Credentials = new System.Net.NetworkCredential( smtpServer.Credentials.UserName, smtpServer.Credentials.Password );
                        smtpClient.EnableSsl = true;
                    }
                }
                else {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;

                    var pickupFolderPath = EwlStatics.CombinePaths( ConfigurationStatics.RedStaplerFolderPath, "Outgoing Dev Mail" );
                    Directory.CreateDirectory( pickupFolderPath );
                    smtpClient.PickupDirectoryLocation = pickupFolderPath;
                }

                using( var m = new System.Net.Mail.MailMessage() ) {
                    m.From = message.From.ToMailAddress();
                    addAddressesToMailAddressCollection( message.ReplyToAddresses, m.ReplyToList );

                    addAddressesToMailAddressCollection( message.ToAddresses, m.To );
                    addAddressesToMailAddressCollection( message.CcAddresses, m.CC );
                    addAddressesToMailAddressCollection( message.BccAddresses, m.Bcc );

                    m.Subject = message.Subject;

                    foreach( var i in message.CustomHeaders )
                        m.Headers.Add( i.Item1, i.Item2 );

                    m.Body = htmlToPlainText( message.BodyHtml );

                    // Add an alternate view for the HTML part.
                    m.AlternateViews.Add(
                        System.Net.Mail.AlternateView.CreateAlternateViewFromString( message.BodyHtml, new System.Net.Mime.ContentType( ContentTypes.Html ) ) );

                    foreach( var attachment in message.Attachments )
                        m.Attachments.Add( attachment.ToAttachment() );

                    try {
                        smtpClient.Send( m );
                    }
                    catch( System.Net.Mail.SmtpException e ) {
                        throw new EmailSendingException( "Failed to send an email message using an SMTP server.", e );
                    }
                }
            }
            finally {
                // Microsoft's own dispose method fails to work if Host is not specified, even though Host doesn't need to be specified for operation.
                if( !string.IsNullOrEmpty( smtpClient.Host ) )
                    smtpClient.Dispose();
            }
        }
Exemplo n.º 42
0
        public void SendEmail(string pSubject, string pDetall, string pEmailDestination)
        {
            System.Net.Mail.MailMessage vMmsg = new System.Net.Mail.MailMessage();

            string vEmailServer = System.Configuration.ConfigurationManager.AppSettings["EMAILSERVER"];
            string vEmailPsw = System.Configuration.ConfigurationManager.AppSettings["EMAILPSW"];
            string vHost = System.Configuration.ConfigurationManager.AppSettings["EMAILHOST"];

            vMmsg.To.Add(pEmailDestination);
            string vSubject = pSubject;
            vMmsg.Subject = vSubject;
            vMmsg.SubjectEncoding = System.Text.Encoding.UTF8;

            vMmsg.Body = pDetall;
            vMmsg.BodyEncoding = System.Text.Encoding.UTF8;
            vMmsg.IsBodyHtml = false;

            vMmsg.From = new System.Net.Mail.MailAddress(vEmailServer);

            System.Net.Mail.SmtpClient vCliente = new System.Net.Mail.SmtpClient();

            vCliente.Credentials =
                new System.Net.NetworkCredential(vEmailServer, vEmailPsw);
            vCliente.Host = vHost;

            try
            {
                vCliente.Send(vMmsg);
                vCliente.Dispose();
            }
            catch (System.Net.Mail.SmtpException ex)
            {
            }
        }
Exemplo n.º 43
-1
        public static bool SendSenha(string nome, string from, string to, string subject, string mensagem)
        {
            System.Net.Mail.SmtpClient s = null;
            try
            {
                s = new System.Net.Mail.SmtpClient("smtp.live.com", 587);
                s.EnableSsl = true;
                s.UseDefaultCredentials = false;
                s.Credentials = new System.Net.NetworkCredential("*****@*****.**", "bandtec1234");
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(
                    new System.Net.Mail.MailAddress(from),
                    new System.Net.Mail.MailAddress(to));
                message.Body = mensagem;
                message.BodyEncoding = Encoding.UTF8;
                message.Subject = subject;
                message.SubjectEncoding = Encoding.UTF8;
                s.Send(message);
                s.Dispose();

                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (s != null)
                    s.Dispose();
            }
        }