Exemple #1
0
        public void ContentStream()
        {
            Attachment attach = Attachment.CreateAttachmentFromString("test", "attachment-name");

            Assert.NotNull(attach.ContentStream);
            Assert.Equal(4, attach.ContentStream.Length);
        }
Exemple #2
0
        private void SetUpAttachment()
        {
            var attachment = Attachment.CreateAttachmentFromString("Attachment Content", "Attachment Name");

            _emailAttachmentGenerator.Setup(mock => mock.CreateAttachmentFile(_report, It.IsAny <string>(), It.IsAny <AttachmentType>(), It.IsAny <string>()))
            .Returns(attachment);
        }
Exemple #3
0
        public void ContentDisposition()
        {
            Attachment attach = Attachment.CreateAttachmentFromString("test", "attachment-name");

            Assert.NotNull(attach.ContentDisposition);
            Assert.Equal("attachment", attach.ContentDisposition.DispositionType);
        }
        public static void SendMail(string bodyMsg, string errors, MailSettings settings)
        {
            var    fromAddress  = new MailAddress(settings.Email, settings.SenderName);
            var    toAddress    = new MailAddress(settings.ToEmail, settings.ToName);
            string fromPassword = settings.Password;
            string subject      = $"CRM job report - {DateTime.Now:dd.MM.yyyy}";
            string body         = bodyMsg;

            var smtp = new SmtpClient
            {
                Host                  = settings.SmtpHost,
                Port                  = settings.Port,
                EnableSsl             = settings.EnableSsl,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body,
                IsBodyHtml = true
            })
            {
                if (errors != string.Empty)
                {
                    message.Attachments.Add(Attachment.CreateAttachmentFromString(errors, $"error_log_{DateTime.Now:yyyyMMdd}.txt"));
                }
                smtp.Send(message);
            }
        }
Exemple #5
0
    private static void BuildAndSendEmail()
    {
        var version  = metricsProcessor.GetMetric <string>(MetricsProcessor.Category.System, "support.metrics.system.version");
        var category = metricsProcessor.GetMetric <string>(MetricsProcessor.Category.Form, "support.category");
        var email    = metricsProcessor.GetMetric <string>(MetricsProcessor.Category.Form, "support.email");

        GetEmails(email, out string from, out string cc);

        var subject = String.Format(SUBJECT_FORMAT, version, category);

        var body = GetBody();

        EmailMessage supportEmail = new EmailMessage
        {
            EmailFormat  = EmailFormatEnum.Html,
            From         = from,
            CcRecipients = cc,
            Subject      = subject,
            Recipients   = SUPPORT_EMAIL,
            Body         = body,
        };

        // Create attachment from metrics JSON
        var metricsAttachment = Attachment.CreateAttachmentFromString(metricsProcessor.JSON, "Instance metrics.json");

        metricsAttachment.ContentType = new ContentType("application/json");

        // Attach metrics JSON and other attachments to email
        supportEmail.Attachments.Add(metricsAttachment);
        metricsProcessor.Attachments.ForEach(a => supportEmail.Attachments.Add(a));

        // Send email
        EmailSender.SendEmail(supportEmail);
    }
Exemple #6
0
        public void SendSmtpSimple(Email email)
        {
            SmtpClient        smtpClient      = new SmtpClient();
            NetworkCredential basicCredential =
                //new NetworkCredential("machete-dcd9269ea5afcbe7", "e16356c22f5a4c13");
                new NetworkCredential(_emCfg.userName, _emCfg.password);
            MailMessage message     = new MailMessage();
            MailAddress fromAddress = new MailAddress(_emCfg.fromAddress);

            smtpClient.Host = _emCfg.host;
            smtpClient.Port = _emCfg.port;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials           = basicCredential;
            smtpClient.EnableSsl             = _emCfg.enableSSL;

            message.From       = fromAddress;
            message.Subject    = email.subject;
            message.IsBodyHtml = true;
            message.Body       = email.body;
            message.To.Add(email.emailTo);
            if (email.attachment != null)
            {
                var a = Attachment.CreateAttachmentFromString(email.attachment, email.attachmentContentType);
                a.Name = "Order.html";
                message.Attachments.Add(a);
            }

            smtpClient.Send(message);
            email.statusID  = Email.iSent;
            email.emailFrom = fromAddress.Address;
        }
Exemple #7
0
        public AttachmentBuilder(StringAttachment stringAtt, Encoding characterEncoding, TransferEncoding textTransferEncoding,
                                 TransferEncoding binaryTransferEncoding)
        {
            string displayName = ShortNameFromFile(stringAtt.DisplayName);

            _attachment = Attachment.CreateAttachmentFromString(stringAtt.Content, displayName, characterEncoding,
                                                                stringAtt.MimeType);
            _attachment.ContentType.MediaType               = stringAtt.MimeType;
            _attachment.ContentDisposition.Inline           = false;
            _attachment.ContentDisposition.FileName         = displayName;
            _attachment.ContentDisposition.CreationDate     = DateTime.Now;
            _attachment.ContentDisposition.ModificationDate = DateTime.Now;
            _attachment.ContentDisposition.ReadDate         = DateTime.Now;
            // Use predefined att.ContentId
            _attachment.NameEncoding = characterEncoding;

            // Take care of correct encoding for the file name, otherwise
            // _attachment.TransferEncoding will throw FormatException 'MailHeaderFieldInvalidCharacter'
            Bugfixer.CorrectAttachmentFileNameEncoding(_attachment, characterEncoding);

            if (_attachment.ContentType.MediaType.ToLower().StartsWith("text/"))
            {
                _attachment.ContentType.CharSet = characterEncoding.HeaderName;
                _attachment.TransferEncoding    = Tools.IsSevenBit(_attachment.ContentStream, characterEncoding)
                                                                ? TransferEncoding.SevenBit
                                                                : textTransferEncoding;
            }
            else
            {
                _attachment.ContentType.CharSet = null;
                _attachment.TransferEncoding    = binaryTransferEncoding;
            }
        }
Exemple #8
0
        void SendEmail(string email, bool xml, bool html)
        {
            List <Attachment> Files   = new List <Attachment>();
            List <string>     domains = new List <string>();

            if (xml)
            {
                foreach (string domain in xmlreports.Keys)
                {
                    if (!domains.Contains(domain))
                    {
                        domains.Add(domain);
                    }
                    Files.Add(Attachment.CreateAttachmentFromString(xmlreports[domain], "ad_hc_" + domain + ".xml"));
                }
            }
            if (html)
            {
                foreach (string domain in htmlreports.Keys)
                {
                    if (!domains.Contains(domain))
                    {
                        domains.Add(domain);
                    }
                    Files.Add(Attachment.CreateAttachmentFromString(htmlreports[domain], "ad_hc_" + domain + ".html"));
                }
            }
            SendEmail(email, domains, Files);
        }
Exemple #9
0
        public void TestSendWithAttachment()
        {
            //Arrange
            EmailSender client  = new EmailSender();
            string      subject = "Email Sender Unit Test Attachment";
            string      body    = "Email Sender Unit Test Attachment";

            MemoryStream ms       = new MemoryStream();
            string       content  = "Email Sender 測試附件";
            Attachment   attach   = Attachment.CreateAttachmentFromString(content, "test.txt");
            Exception    expected = null;

            //Act
            Exception result = null;

            try
            {
                client.Send(subject, body, to, null, attach, true);
            }
            catch (Exception ex)
            {
                result = ex;
            }

            //Assert
            Assert.AreEqual(expected, result);
        }
    public static void SendEmail(string subject, string body, string attachment = null)
    {
        var          fromAddress  = new MailAddress("*****@*****.**", "StructuredXmlEditor");
        var          toAddress    = new MailAddress("*****@*****.**", "Philip Collin");
        const string fromPassword = "******";

        var smtp = new SmtpClient
        {
            Host                  = "smtp.gmail.com",
            Port                  = 587,
            EnableSsl             = true,
            DeliveryMethod        = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
        };

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject, Body = body
        })
        {
            if (attachment != null)
            {
                message.Attachments.Add(Attachment.CreateAttachmentFromString(attachment, "Attachment.txt"));
            }

            smtp.Send(message);
        }
    }
        public static void Run()
        {
            // ExStart:CreateREAndFWMessages
            string dataDir = RunExamples.GetDataDir_Exchange();

            const string      mailboxUri = "https://exchange.domain.com/ews/Exchange.asmx";
            const string      domain     = @"";
            const string      username   = @"username";
            const string      password   = @"password";
            NetworkCredential credential = new NetworkCredential(username, password, domain);
            IEWSClient        client     = EWSClient.GetEWSClient(mailboxUri, credential);

            try
            {
                MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**", "TestMailRefw - " + Guid.NewGuid().ToString(),
                                                      "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

                client.Send(message);

                ExchangeMessageInfoCollection messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);
                if (messageInfoCol.Count == 1)
                {
                    Console.WriteLine("1 message in Inbox");
                }
                else
                {
                    Console.WriteLine("Error! No message in Inbox");
                }

                MailMessage message1 = new MailMessage("*****@*****.**", "*****@*****.**", "TestMailRefw - " + Guid.NewGuid().ToString(),
                                                       "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

                client.Send(message1);
                messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);

                if (messageInfoCol.Count == 2)
                {
                    Console.WriteLine("2 messages in Inbox");
                }
                else
                {
                    Console.WriteLine("Error! No new message in Inbox");
                }

                MailMessage message2 = new MailMessage("*****@*****.**", "*****@*****.**", "TestMailRefw - " + Guid.NewGuid().ToString(),
                                                       "TestMailRefw Implement ability to create RE and FW messages from source MSG file");
                message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1"));
                message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2"));

                // Reply, Replay All and forward Message
                client.Reply(message2, messageInfoCol[0]);
                client.ReplyAll(message2, messageInfoCol[0]);
                client.Forward(message2, messageInfoCol[0]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in program" + ex.Message);
            }
            // ExEnd:CreateREAndFWMessages
        }
Exemple #12
0
        public void SendMailWithAttachment(string mailDestinatarios, string asunto, string mensaje, string attachmentName)
        {
            MailMessage correo = new MailMessage();

            Attachment attach = Attachment.CreateAttachmentFromString(mensaje, attachmentName);

            string[] destinatarios = mailDestinatarios.Split(';');

            foreach (string word in destinatarios)
            {
                correo.To.Add(word);
            }

            correo.From = new MailAddress(DIRECCION_CORREO_FROM, ALIAS_CORREO_FROM);

            correo.Subject    = asunto;
            correo.Body       = mensaje;
            correo.IsBodyHtml = true;
            correo.Attachments.Add(attach);
            correo.BodyEncoding = Encoding.UTF8;
            correo.Priority     = MailPriority.High;
            SmtpClient smtp = new SmtpClient();

            smtp.Host        = HOST_MAILS;
            smtp.EnableSsl   = HABILITAR_SSL;
            smtp.Port        = NUMERO_PUERTO;
            smtp.Timeout     = 10000000;
            smtp.Credentials = new System.Net.NetworkCredential(USUARIO_CUENTA, PASSWORD_CUENTA);

            smtp.Send(correo);
        }
 /// <summary>
 ///     Creates a mail attachment using the content from the specified string, the specified MIME content type name,
 ///     character encoding, and MIME header information for the attachment.
 /// </summary>
 /// <param name="content">A <see cref="T:System.String" /> that contains the content for this attachment.</param>
 /// <param name="name">The MIME content type name value in the content type associated with this attachment.</param>
 /// <param name="contentEncoding">An <see cref="T:System.Text.Encoding" />. This value can be <see langword="null" />.</param>
 /// <param name="mediaType">
 ///     A <see cref="T:System.String" /> that contains the MIME Content-Header information for this
 ///     attachment. This value can be <see langword="null" />.
 /// </param>
 /// <returns>An object of type <see cref="T:Snork.SerializableMail.SerializableAttachment" />.</returns>
 public static SerializableAttachment CreateAttachmentFromString(
     string content,
     string name,
     Encoding contentEncoding,
     string mediaType)
 {
     return(Attachment.CreateAttachmentFromString(content, name, contentEncoding, mediaType));
 }
 Attachment GetAttachmentFromMessage(RestMSMessageContent content)
 {
     return(Attachment.CreateAttachmentFromString(
                content.Value,
                Guid.NewGuid().ToString(),
                Encoding.GetEncoding(content.Encoding),
                content.Type));
 }
        private void AddAttachement(MailMessage mail)
        {
            var attachment = Attachment.CreateAttachmentFromString(
                "contents of the attachement",
                MediaTypeNames.Text.Plain);

            mail.Attachments.Add(attachment);
        }
Exemple #16
0
        public void EnviarFacturaXML(int ID_Factura)
        {

            List<Producto> productos;
            productos = Repositorio.ObtenerProductosDeFactura(ID_Factura);
            Persona Cliente = Repositorio.ObtenerClienteDeFactura(ID_Factura);
            Factura factura = Repositorio.ObtenerFacturaPorID(ID_Factura);
            FacturaDetallada facturaDetallada = new FacturaDetallada();
            facturaDetallada.FechaEmision = factura.FechaEmision;
            facturaDetallada.NombreComercial = factura.NombreComercial;
            facturaDetallada.ListaDeProductos = productos;
            facturaDetallada.MontoTotal = factura.MontoTotal;
            facturaDetallada.Cliente = Cliente;

            String To = Cliente.CorreoElectronico;
            String Subject = "Factura de compras";
            String Body = Cliente.PrimerNombre + ", le agradecemos por su compra. Vuelva pronto.";
            MailMessage mailMessage = new MailMessage();
            mailMessage.To.Add(To);
            mailMessage.Subject = Subject;
            mailMessage.Body = Body;
            mailMessage.From = new MailAddress(Cliente.CorreoElectronico);
            mailMessage.IsBodyHtml = false;

            string facturaYClienteInfo =
    "<?xml version=\"1.0\" encoding=\"utf - 8\" ?>\n" +
    "< !--Factura.xml stores information about Mahesh Chand and related books -->\n" +
    "< Facturas >\n" +
        "\t< Factura Fecha de emision = \"" + factura.FechaEmision + "\" Monto total = \"" + factura.MontoTotal + "\" Comercio = \""
        + factura.NombreComercial + "\" >\n" +
            "\t\t< Cliente >" + Cliente.PrimerNombre + " " + Cliente.SegundoNombre + " " + Cliente.PrimerApellido + " " + Cliente.SegundoApellido + " </Cliente>\n";
            string productosInfo = "";
            foreach (var producto in productos)
            {
                productosInfo =
            "\t\t< Producto >\n" +
                "\t\t\t< Nombre > " + producto.Nombre + " </ Nombre >\n" +
                "\t\t\t< Detalle > " + producto.Detalle + " </ Detalle >\n" +
                "\t\t\t< Precio unitario > " + producto.PrecioUnitario + " </ Precio unitario >\n" +
            "\t\t</ Producto >\n"
            + productosInfo;

            }
            string finalDeLaCadena =
        "\t</ Factura >\n" +
     "</ Facturas > \n";
            String xmlCompleto = facturaYClienteInfo + productosInfo + finalDeLaCadena;


            mailMessage.Attachments.Add(Attachment.CreateAttachmentFromString(xmlCompleto, "Factura.xml"));

            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
            smtpClient.Port = 587;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.EnableSsl = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "contra segur@ 23");
            smtpClient.Send(mailMessage);
        }
Exemple #17
0
        /// <summary>
        /// Takes the given text content, and creates a Mail attachment.
        /// Gives the attachment the given file name
        /// </summary>
        /// <param name="textContent">Body of the attachment</param>
        /// <param name="fileName">Filename for this attachment</param>
        /// <returns></returns>
        public static Attachment CreateMailAttachmentFromString(string textContent, string fileName)
        {
            Attachment attachment = Attachment.CreateAttachmentFromString(textContent, fileName);

            attachment.ContentDisposition.DispositionType = "attachment";
            attachment.ContentDisposition.FileName        = fileName;

            return(attachment);
        }
Exemple #18
0
        public void Name()
        {
            Attachment attach = Attachment.CreateAttachmentFromString("test", "attachment-name");

            Assert.Equal("attachment-name", attach.Name);
            Attachment a2 = new Attachment(new MemoryStream(), new ContentType("image/jpeg"));

            Assert.Null(a2.Name);
            a2.Name = null; // nullable
        }
Exemple #19
0
        public void ContentType()
        {
            Attachment attach = Attachment.CreateAttachmentFromString("test", "attachment-name");

            Assert.NotNull(attach.ContentType);
            Assert.Equal("text/plain", attach.ContentType.MediaType);
            Attachment a2 = new Attachment(new MemoryStream(), "myname");

            Assert.NotNull(a2.ContentType);
            Assert.Equal("application/octet-stream", a2.ContentType.MediaType);
        }
Exemple #20
0
        public void NameEncoding()
        {
            Attachment attach = Attachment.CreateAttachmentFromString("test", "attachment-name");

            Assert.Null(attach.NameEncoding);
            Attachment a = new Attachment(new MemoryStream(), "myname");

            Assert.Null(a.NameEncoding);
            a = new Attachment(new MemoryStream(), "myname\u3067");
            Assert.Null(a.NameEncoding);
        }
Exemple #21
0
        public MailMessageTest()
        {
            messageWithSubjectAndBody         = new MailMessage("*****@*****.**", "*****@*****.**");
            messageWithSubjectAndBody.Subject = "the subject";
            messageWithSubjectAndBody.Body    = "hello";
            messageWithSubjectAndBody.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><body>hello</body></html>", null, "text/html"));
            Attachment a = Attachment.CreateAttachmentFromString("blah blah", "text/plain");

            messageWithSubjectAndBody.Attachments.Add(a);

            emptyMessage = new MailMessage("*****@*****.**", "[email protected], [email protected]");
        }
Exemple #22
0
 public bool AdvancedLiveAnalysisTask()
 {
     return(StartTask("Compromission Graph analysis",
                      () =>
     {
         DisplayAdvancement("Doing the data collection");
         ExportDataFromActiveDirectoryLive export = new ExportDataFromActiveDirectoryLive(Server, ADWSPort, Credential);
         export.ExportData(NodesToInvestigate);
         DisplayAdvancement("Doing the analysis");
         ReportGenerator reporting = new ReportGenerator(export.Storage, MaxDepth, MaxNodes);
         var data = reporting.GenerateReport(NodesToInvestigate);
         DisplayAdvancement("Generating the report");
         var reportGenerator = new HealthCheckReportCompromiseGraph(data, License);
         reportGenerator.GenerateReportFile("ad_cg_" + data.DomainFQDN + ".html");
         string xml = DataHelper <CompromiseGraphData> .SaveAsXml(data, "ad_cg_" + data.DomainFQDN + ".xml", EncryptReport);
         if (!String.IsNullOrEmpty(apiKey) && !String.IsNullOrEmpty(apiEndpoint))
         {
             SendViaAPI(new Dictionary <string, string>()
             {
                 { FileOrDirectory, xml }
             });
         }
         if (!String.IsNullOrEmpty(sharepointdirectory))
         {
             UploadToWebsite("ad_cg_" + data.DomainFQDN + ".xml", xml);
         }
         if (!String.IsNullOrEmpty(sendXmlTo))
         {
             SendEmail(sendXmlTo, new List <string> {
                 data.DomainFQDN
             },
                       new List <Attachment> {
                 Attachment.CreateAttachmentFromString(xml, "ad_cg_" + data.DomainFQDN + ".xml")
             });
         }
         if (!String.IsNullOrEmpty(sendHtmlTo))
         {
             WriteInRed("Html report ignored when xml file used as input");
         }
         if (!String.IsNullOrEmpty(sendAllTo))
         {
             WriteInRed("Html report ignored when xml file used as input");
             SendEmail(sendAllTo, new List <string> {
                 data.DomainFQDN
             },
                       new List <Attachment> {
                 Attachment.CreateAttachmentFromString(xml, "ad_cg_" + data.DomainFQDN + ".xml")
             });
         }
         DisplayAdvancement("Done");
     }
                      ));
 }
Exemple #23
0
        private static byte[] DecodeData(string data, string encoding)
        {
            switch (encoding)
            {
            case "base64": return(Convert.FromBase64String(data));

            case "7bit":
            case "8bit":
            case "binary": return(Encoding.ASCII.GetBytes(data));

            case "quoted-printable": return(Encoding.UTF8.GetBytes(Attachment.CreateAttachmentFromString("", data).Name));

            default: throw new Exception($"Content transfer encoding of type {encoding} not supported.");
            }
        }
Exemple #24
0
        public async Task CanVerifyCallsOnSmtpImposter()
        {
            const int    port               = 6000;
            const string from               = "*****@*****.**";
            const string to1                = "*****@*****.**";
            const string to2                = "*****@*****.**";
            const string subject            = "Test Subject";
            const string body               = "Test Body";
            const string attachmentContent1 = "Test Content1";
            const string attachmentContent2 = "Test Content2";

            var imposter = _client.CreateSmtpImposter(port, recordRequests: true);
            await _client.SubmitAsync(imposter);

            var mail = new MailMessage
            {
                From    = new MailAddress(from),
                Subject = subject,
                Body    = body
            };

            mail.To.Add(to1);
            mail.To.Add(to2);

            var attachment1 = Attachment.CreateAttachmentFromString(attachmentContent1, new ContentType("text/plain"));
            var attachment2 = Attachment.CreateAttachmentFromString(attachmentContent2, new ContentType("text/plain"));

            mail.Attachments.Add(attachment1);
            mail.Attachments.Add(attachment2);

            var smtpClient = new SmtpClient("localhost")
            {
                Port = port
            };

            await smtpClient.SendMailAsync(mail);

            var retrievedImposter = await _client.GetSmtpImposterAsync(port);

            Assert.AreEqual(1, retrievedImposter.NumberOfRequests);
            Assert.AreEqual(from, retrievedImposter.Requests.First().EnvelopeFrom);
            Assert.AreEqual(to1, retrievedImposter.Requests.First().EnvelopeTo.First());
            Assert.AreEqual(to2, retrievedImposter.Requests.First().EnvelopeTo.Last());
            Assert.AreEqual(subject, retrievedImposter.Requests.First().Subject);
            Assert.AreEqual(body, retrievedImposter.Requests.First().Text);
            Assert.AreEqual(attachmentContent1, Encoding.UTF8.GetString(retrievedImposter.Requests.First().Attachments.First().Content.Data));
            Assert.AreEqual(attachmentContent2, Encoding.UTF8.GetString(retrievedImposter.Requests.First().Attachments.Last().Content.Data));
        }
Exemple #25
0
        public void Execute(ErrorLog errorLog)
        {
            if (string.IsNullOrWhiteSpace(Settings.To))
            {
                return;
            }
            dynamic email = new Email("ErrorLog");

            email.From            = Settings.From ?? "elfar@" + errorLog.Host;
            email.To              = Settings.To;
            email.Subject         = string.Format(Settings.SubjectFormat ?? "Error ({0}): {1}", errorLog.Type, errorLog.Message).Replace(@"\r\n", " ");
            email.Time            = errorLog.Time;
            email.Detail          = errorLog.Detail;
            email.ServerVariables = errorLog.ServerVariables;
            if (Settings.AttachOriginalError && !string.IsNullOrWhiteSpace(errorLog.Html))
            {
                email.Attach(Attachment.CreateAttachmentFromString(errorLog.Html, "Original ASP.NET error page.html", Encoding.UTF8, "text/html"));
            }
            email.SendAsync();
        }
        public Attachment CreateAttachment(
            string templatePath,
            object model,
            string mediaType = "text/plain")
        {
            Type modelType = GetModelType(model);

            CompileAndCacheTemplate(templatePath, modelType);

            var     viewBag        = new DynamicViewBag();
            dynamic dynamicViewBag = viewBag;

            string content = Engine.Razor.Run(templatePath, modelType, model, viewBag);

            var attachment = Attachment.CreateAttachmentFromString(content, mediaType);

            attachment.ContentDisposition.FileName = dynamicViewBag.FileName;

            return(attachment);
        }
Exemple #27
0
        //發送郵件
        public static bool SendHMail(HMailInfo hMailInfo)
        {
            MailMessage msg = new MailMessage();

            msg.From = hMailInfo.From;
            foreach (MailAddress mail in hMailInfo.To)
            {
                msg.To.Add(mail);
            }
            foreach (MailAddress mail in hMailInfo.Cc)
            {
                msg.CC.Add(mail);
            }
            foreach (MailAddress mail in hMailInfo.Bcc)
            {
                msg.Bcc.Add(mail);
            }
            foreach (HMailAttachmentInfo mail in hMailInfo.Attachments)
            {
                msg.Attachments.Add(Attachment.CreateAttachmentFromString(Encoding.GetEncoding(mail.Encoding).GetString(mail.FileBuffer), mail.ContentType));
            }
            StringBuilder strBud = new StringBuilder();

            foreach (HMailContentInfo mail in hMailInfo.ContentInfo)
            {
                strBud.Append(mail.Content);
            }
            msg.Body         = strBud.ToString();
            msg.IsBodyHtml   = true;
            msg.BodyEncoding = msg.SubjectEncoding = Encoding.UTF8;
            try
            {
                smtpClient.Send(msg);
                return(true);
            }
            catch (Exception ex)
            {
                SendMailFAailedEvent(ex);
                return(false);
            }
        }
Exemple #28
0
        public void Send_Email_With_AlternateViews_And_Attachments()
        {
            using (var client = new SmtpClient("localhost", this.server.Configuration.Port))
            {
                var mailMessage = new MailMessage("*****@*****.**", "*****@*****.**", "test", "this is the body");
                mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("FooBar", new ContentType("text/html")));
                mailMessage.Attachments.Add(Attachment.CreateAttachmentFromString("Attachment1", new ContentType("application/octet-stream")));
                mailMessage.Attachments.Add(Attachment.CreateAttachmentFromString("Attachment2", new ContentType("application/octet-stream")));
                mailMessage.Attachments.Add(Attachment.CreateAttachmentFromString("Attachment3", new ContentType("application/octet-stream")));
                client.Send(mailMessage);
            }

            Assert.Equal(1, this.server.ReceivedEmailCount);
            var smtpMessage = this.server.ReceivedEmail[0];

            Assert.Equal(5, smtpMessage.MessageParts.Length);
            Assert.True(smtpMessage.MessageParts[0].HeaderData.Contains("text/plain"));
            Assert.Equal("this is the body", smtpMessage.MessageParts[0].BodyData);
            Assert.True(smtpMessage.MessageParts[1].HeaderData.Contains("text/html"));
            Assert.Equal("FooBar", smtpMessage.MessageParts[1].BodyData);
        }
Exemple #29
0
        public AttachmentInstance CreateAttachmentFromString(string content, string name, object encoding, object contentType)
        {
            if (encoding == Undefined.Value && contentType == Undefined.Value)
            {
                return(new AttachmentInstance(this.Engine, Attachment.CreateAttachmentFromString(content, name)));
            }

            var enc = encoding as EncodingInstance;

            var actualEncoding = enc == null
                ? Encoding.GetEncoding(TypeConverter.ToString(encoding))
                : enc.Encoding;

            if (enc == null)
            {
                actualEncoding = Encoding.Default;
            }

            var ct = TypeConverter.ToString(contentType);

            return(new AttachmentInstance(this.Engine, Attachment.CreateAttachmentFromString(content, name, actualEncoding, ct)));
        }
        public void TestSendingMailWithAttachment()
        {
            var address = new MailAddress("*****@*****.**", "Test User", Encoding.UTF8);
            var msg     = new MailMessage(address, address)
            {
                IsBodyHtml = true
            };
            var attachment = Attachment.CreateAttachmentFromString("test test test", "file.txt");

            attachment.ContentDisposition.FileName = "file.txt";

            msg.Body = "body body body";

            msg.Attachments.Add(attachment);

            byte[] serialized = MailMessageBinarySerializer.Serialize(msg);

            using (var client = new SmtpClient("10.10.104.138", 25))
                using (var msg2 = MailMessageBinarySerializer.Deserialize(serialized)) {
                    client.Send(msg2);
                }
        }