Como ler HTML de uma página web e usá-lo como corpo de HTML auto-Responder E-Mail

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

  •  19-09-2019
  •  | 
  •  

Pergunta

Eu estou trabalhando em um e-mail HTML de resposta automática. Se há uma maneira mais simples do que o que estou fazendo por favor me avise.

Até agora, eu construí "pagename.aspx" e eu ler esta página em uma variável de cadeia, em seguida, usar essa variável como o corpo do e-mail. Isso funciona.

A página opcionalmente aceita uma QueryString chamado "leadID". Isto é usado para extrair dados de um banco de dados e campos Preencher nesta página. Isso também funciona bem quando eu navegar manualmente para a página -? Pagename.aspx leadid = xyz

Meu Problema / Pergunta é , como faço para passar este querystring para a página e retornar a saída HTML resultante da página em uma string, que pode então ser usado como o corpo do meu e-mail.

Mais uma vez, se há uma maneira melhor por favor me avise. Eu estou usando LINQ to SQL, VB.NET e ASP.NET 3.5.

Graças um milhão.

Foi útil?

Solução

A maneira mais fácil é apenas para fazer um WebRequest a ele:

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

Outras dicas

Como descrito neste artigo , você poderia usar o HttpWebRequest classe para recuperar o fluxo de dados a partir da página "pagename.aspx? leadID = 1". Mas isso pode causar um pouco de sobrecarga para a sua aplicação devido à solicitação HTTP adicional.

Não seria possível / melhor para gerar o conteúdo HTML de uma classe simples? O conteúdo gera sua página?

Edit: Como solicitado por Khalid aqui é uma classe simples para gerar um arquivo HTML dinâmico usando o parâmetro leadID e um controle gridview. É apenas um exemplo, você precisaria de costume-lo e fazer mais reutilizáveis:

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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top