Cómo leer HTML de una página web y utilizarlo como cuerpo de HTML Auto-Responder E-Mail

StackOverflow https://stackoverflow.com/questions/1507351

  •  19-09-2019
  •  | 
  •  

Pregunta

Estoy trabajando en un correo electrónico HTML respuesta automática. Si hay una manera más sencilla que lo que estoy haciendo por favor hágamelo saber.

Hasta ahora, he construido "pagename.aspx" y he leído esta página en una variable de cadena, a continuación, utilizar esta variable como el cuerpo del correo. Esto funciona.

La página acepta opcionalmente una cadena de consulta llamado "leadID". Esto se utiliza para extraer datos de una base de datos y rellenar los campos en esta página. Esto también funciona bien cuando hojeo manualmente a la página - pagename.aspx leadid = xyz

Mi Problema / pregunta es , ¿Cómo puedo pasar esta cadena de consulta de la página y devolver la salida HTML resultante de la página en una cadena, que puede ser utilizado como el cuerpo de mi correo electrónico.

Una vez más, si hay una mejor manera por favor hágamelo saber. Estoy usando LINQ a SQL, VB.NET y ASP.NET 3.5.

Un millón de gracias.

¿Fue útil?

Solución

La forma más fácil es sólo para hacer un WebRequest a ella:

string url = "...";
string result;

HttpWebRequest webrequest = (HttpWebRequest) HttpWebRequest.Create(url);
webrequest.Method        = "GET";
webrequest.ContentLength = 0;

WebResponse response = webrequest.GetResponse();

using(StreamReader stream = new StreamReader(response.GetResponseStream())){
    result = stream.ReadToEnd();
}

Otros consejos

Como se describe en este artículo , se puede utilizar el HttpWebRequest clase para recuperar el flujo de datos desde la página de "pagename.aspx? leadID = 1". Pero eso podría causar un poco de sobrecarga para su aplicación debido a la petición HTTP adicional.

¿No sería posible / mejor para generar su contenido HTML de una clase simple? ¿Qué contenido genera la página?

Editar: Como se le preguntó por Khalid aquí hay una clase simple para generar un archivo HTML dinámico utilizando el parámetro leadID y un control GridView. Es sólo un ejemplo, se necesitaría la costumbre y hacer más reutilizables:

using System;
using System.Text;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;

public class PageBroker
{

    /*
     * How to use PageBroker:
     * 
     *  string leadID = "xyz"; // dynamic querystring parameter
     *  string pathToHTML = Server.MapPath(".") + "\\HTML\\leadForm.html"; //more detail about this file below
     *  PageBroker pLeadBroker = new PageBroker(pathToHTML, leadID);  
     *  Response.Write(pLeadBroker.GenerateFromFile()); // will show content of generated page
     */

    private string _pathToFile;
    private StringBuilder _fileContent;
    private string _leadID;

    public PageBroker(string pathToFile, string leadID)
    {
        _fileContent = new StringBuilder();
        _pathToFile = pathToFile;
        _leadID = leadID;
    }

    public string GenerateFromFile() {
        return LoadFile();
    }
    private string LoadFile()
    {
        // Grab file and load content inside '_fileContent'
        // I used an html file to create the basic structure of your page
        // but you can also create
        // a page from scratch.
        if (File.Exists(_pathToFile))
        {
            FileStream stream = new FileStream(_pathToFile, FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(stream);
            while (reader.Peek() > -1)
                _fileContent.Append(reader.ReadLine() + "\n");
            stream.Close();
            reader.Close();

            InjectTextContent();
            InjectControlsContent();
        }        
        return _fileContent.ToString();
    }

    // (Ugly) method to inject dynamic values inside the generated html
    // You html files need to contain all the necesary tags to place your
    // content (for example: '__USER_NAME__')
    // It would be more OO if a dictionnary object was passed to the 
    // constructor of this class and then used inside this method 
    // (I leave it hard-coded for the sake of understanding but 
    // I can give you a more detailled code if you need it).
    private void InjectTextContent() {
        _fileContent.Replace("__USER_NAME__", "Khalid Rahaman");
    }

    // This method add the render output of the controls you need to place
    // on the page. At this point you will make use of your leadID parameter,
    // I used a simple array with fake data to fill the gridview.
    // You can add whatever control you need.
    private void InjectControlsContent() {
        string[] products = { "A", "B", "C", "D" };
        GridView gvProducts = new GridView();
        gvProducts.DataSource = products;
        gvProducts.DataBind();

        // HtmlTextWriter is used to write HTML programmatically. 
        // It provides formatting capabilities that ASP.NET server 
        // controls use when rendering markup to clients 
        // (http://msdn.microsoft.com/en- us/library/system.web.ui.htmltextwriter.aspx)
        // This way you will be able to inject the griview's 
        // render output inside your file.
        StringWriter gvProductsWriter = new StringWriter();
        HtmlTextWriter htmlWrit = new HtmlTextWriter(gvProductsWriter);
        gvProducts.RenderControl(htmlWrit);
        _fileContent.Replace("__GRIDVIEW_PRODUCTS__", gvProductsWriter.ToString());
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top