Search code examples
c#htmlasp.netemailemail-attachments

How to add a string to a HTML file while sending it as email in asp .net


I am working with asp .net. I want to send an authentication code to user's email when he sign up. I'm using this code to send email. I'm adding a html file to send. How can I add the authentication code to this HTML file?

This is the code which I used to send the html file via Email. So how can I add a string(authenticationCode) to HTML file to send it to the user for authentication.

var fromAddress = new MailAddress("hamza230@gmail.com", "From Hamza");
        var toAddress = new MailAddress("usama90@gmail.com", "To Usama");
        const string fromPassword = "****";
        const string subject = "email";
        const string body = "hello world";

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
            Timeout = 20000
        };
        MailMessage message = new MailMessage(fromAddress, toAddress);
        message.Subject = subject;
        message.Body = body;
        message.BodyEncoding = Encoding.UTF8;

        String plainBody = "Title";

        AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
        message.AlternateViews.Add(plainView);


        MailDefinition msg = new MailDefinition();
        msg.BodyFileName = "~/newsletter.html";

        msg.IsBodyHtml = true;
        msg.From = "usamaazam10@gmail.com";
        msg.Subject = "Subject";

        ListDictionary replacements = new ListDictionary();

        MailMessage msgHtml = msg.CreateMailMessage("usamaazam10@gmail.com", replacements, new LiteralControl());
        AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");

        LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg"), MediaTypeNames.Image.Jpeg);
        logo.ContentId = "logo";
        htmlView.LinkedResources.Add(logo);

        LinkedResource cover = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/cover.jpg"), MediaTypeNames.Image.Jpeg);
        cover.ContentId = "cover";
        htmlView.LinkedResources.Add(cover);

        message.AlternateViews.Add(htmlView);

        smtp.Send(message);

Solution

  • You can do this for small html pages

    string smalHhtml = "<body>"
                       + "your some designing"
                       + "your Code : " + code
                       + "</body>";
    

    Note: This is for small body html and sending verification code via email is usually small html.