0

I have a section in my website where I want to send as an email to user when they click on button send. How can I pass the HTML and it's content to controller and then passing it as the message body to smtpClient

I have

<div id="mydiv">
<div>
<a>Click Here</a>
</div>

</div>

I will like to get all the html and it's content (<div id="mydiv"><div><a>Click Here</a></div></div>) when the id mydiv is called from the controller

Niang Moore
  • 506
  • 5
  • 17

2 Answers2

0

You can use jQuery to intercept the click and construct an ajax request that includes the html of your choice. Accept the html as a string argument with a matching name. Then use the smtp client to forward it to the address of your choice.

<script>
$(document).ready(function () {
    $(document).on("click", "#button1", {}, function (event) {
        event.preventDefault();

        var x = $("#mydiv").html();

        var options = {
            url: "your url",
            method: "POST",
            data: {
                data1: x
            }
        };

        var req = $.ajax(options);

        req.done(function (resp) {
            alert("Email sent");
        });

    });
});
</script>

<div id="mydiv">
<div>
    <a id="button1">Click Here</a>
</div>
</div>


public IActionResult TestAction(string data1)
{
        SmtpClient client = new SmtpClient("smtp_server");
        client.UseDefaultCredentials = false;
        client.Credentials = new NetworkCredential("username", "password");

        MailMessage mailMessage = new MailMessage();
        mailMessage.From = new MailAddress("test@test.com");
        mailMessage.To.Add("test@test.com");
        mailMessage.Body = data1;
        mailMessage.Subject = "subject";
        client.Send(mailMessage);

        return null;//or whatever you want
}
0

I would use an html editor, check ckeditor for example. and here is a tutorial on how to implement it with mvc and when you install the CKEDITOR make sure the config htmlEncodeOutput is true. If you used it, the action might reject the request because it contains dangerous input, you will have to set the validate input to false, or check this for more details

Munzer
  • 2,216
  • 2
  • 18
  • 25