Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MailTo From Javascript

I've got a link button which is used to build up a mailto from the contents of the page. What is the best way to launch it from javascript without opening a blank window or disturbing the window it's called from?

function Email()
{
    var sMailTo = "mailto:";
    var sBody = "";

    var alSelectedCheckboxes = new Array();
    $("input:checkbox[CheckBoxType=Email]:checked").each(function()
    {
        alSelectedCheckboxes.push($(this).val());
    });

    if (alSelectedCheckboxes.length > 0)
    {
        for (var i=0; i<alSelectedCheckboxes.length; i++)
        {
            sBody += alSelectedCheckboxes[i];
            sBody += "\n";
        }

        sMailTo += escape("<Insert Recipients Here>") +"?subject=" +escape("<Insert Subject Here>") +"&body=" +escape(sBody);
        window.location.href = sMailTo;
    }
    else
    {
        alert("Please select some results");
    }
}

The simple function is above. window.location.href doesn't work properly unless it's Firefox/Chrome (it redraws the page in IE8). I've also tried window.open(sMailTo, "_self") but again in IE8 this breaks the page that it's called from.

I'm sure this is a stupid question.... :-)

Thanks

like image 744
Gordon Thompson Avatar asked Mar 10 '11 20:03

Gordon Thompson


People also ask

Can you use JavaScript in emails?

With HTML in your email, you can format the text, incorporate images, and do most of the same things in the email that you can do in a web page. As you can incorporate JavaScript into HTML in a web page, you can of course similarly incorporate JavaScript into HTML in an email.

How do I pass HTML formatted body in mailto?

The Mailto format does not support HTML code emails. Outlook was used at 2003, but to become compliant with the mailto: standard they removed that functionality. But you can Use %0D%0A for a line break in HTML body.


1 Answers

I don't think it's stupid at all! This is a good start. What I'd try next is just to create an actual link object in jquery, append it to the body, and then click() it.

//window.location.href = sMailTo;
$('<a href="' + sMailTo + '">click</a>').appendTo('body').click().remove();

Should work as long as the escape() function you're using gets rid of all of the quotes and correctly encodes the html.

But I have to say, this could be hard to get just right. If it still doesn't work, I'd recommend doing it server-side where the link POSTS all of the html needed.

like image 107
Groovetrain Avatar answered Sep 21 '22 00:09

Groovetrain