📜  mailto - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:31.035000             🧑  作者: Mango

mailto - Javascript

Javascript offers a convenient way to allow website visitors to compose an email, thanks to the mailto function. This function opens a new email, pre-populated with the data that was passed to it.

Syntax

The mailto function can be used with or without parameters, and can accept multiple parameters separated by ampersands (&).

The basic syntax for the mailto function without any parameters is:

window.location.href = "mailto:";

This will open a new email in the user's default email client.

To pre-populate the email, various parameters can be added to the mailto function. The most common parameters are:

  • to: the email address of the recipient
  • cc: the email address of the recipient to be copied
  • bcc: the email address of the recipient to be blind-copied
  • subject: the subject of the email
  • body: the body of the email

For example, the following code will create an email with the subject "Hello" and the body text "Greetings from Javascript":

var emailLink = "mailto:example@gmail.com?subject=Hello&body=Greetings from Javascript";
window.open(emailLink);
Compatibility

The mailto function is supported by most modern browsers, including Chrome, Firefox, Safari, and Edge. However, some email clients may not handle all mailto parameters correctly.

Conclusion

The mailto function in Javascript provides a simple and convenient way for website visitors to send emails. Its usage can be extended by incorporating additional parameters that allow for more customization.

Overall, this function is a useful tool for web developers who want to provide a simple way for website visitors to contact them directly.


Example code snippet:

// opens default email client with new email to the email address
window.location.href = "mailto:example@gmail.com";

// opens email client with pre-populated email details
var emailLink = "mailto:example@gmail.com?cc=jane@gmail.com&subject=Hello&body=Greetings from Javascript";
window.open(emailLink);