Creating email link with dynamically generated body with html5 & javascript

28,552

Solution 1

I just assigned an id to the link here, but you could create something more generic if you wanted. Once you have an onclick handler created you can access the url with href. Set this to whatever you want.

http://jsfiddle.net/f3ZZL/1

var link = document.getElementById('email');
link.onclick = function() {
    this.href = "mailto:[email protected]?subject=Data&body=";
    this.href += getBody();
};

function getBody() {
    return 'HelloWorld';
}

Solution 2

Here is the no-spam method

var link = document.getElementById('email');

link.onclick = function() {
    var name = "you";
    var domain = "yourdomain.com";
    var linker = "mailto:" + name + '@' + domain + "?subject=Data&body=";
    linker += getBody();
    link.setAttribute("href", linker);
};

function getBody() {
    return 'HelloWorld';
}

On Fiddle

Share:
28,552
vinomarky
Author by

vinomarky

A hack of a programmer.... in fact I think that would be giving hacks a bad name. I manage to muddle through enough to make and maintain an iPhone app in html and JavaScript. Apologies in advance for my limited understanding of the fundamentals, programming is not my career, and with three kids and a full time job as an engineer I simply don’t have time to do lots of reading on the topic, and very much appreciate the leg-ups you guys provide here. :-)

Updated on August 19, 2020

Comments

  • vinomarky
    vinomarky over 3 years

    Am trying to create a link to create an email to send information to the user, the body of which needs to be filled with data generated by a javascript function, and hope that someone can help.

    Idealy, if I could substitute the 'body_blurb' below, with a string returned from a javascript function called at the time of clicking that'd be perfect.

    <A HREF="mailto:[email protected]?subject=Data&body=body_blurb">e-mail data</a>
    

    Appreciate your time

  • mrtsherman
    mrtsherman about 12 years
    Hmmm, so you could use location.href = mailto: ...?
  • vinomarky
    vinomarky about 12 years
    Perfect - exactly what I was after. By way of further explanation, I'm creating a simple engineering calculation number cruncher to be accssed via mobile browsers. The user would enter their variables, crunch the numbers and get an output. I'd like to be able to give them the option of sending themselves the data set of inputs & outputs.