Categories
JavaScript Answers

How to Use the window.open Method to Open a mailto URL?

Spread the love

To use the window.open method to open a mailto URL, we can call window.open with '_self' as the 2nd argument.

For instance, we write:

const emailTo = 'example@example.com'
const emailCC = 'cc@example.com'
const emailSub = 'subject'
const emailBody = 'body'
window.open(`mailto:${emailTo}?cc=${emailCC}&subject=${emailSub}&body=${emailBody}`, '_self');

We set the emailTo, emailCC, emailSub and emailBody variables to the values we want.

emailTo is the email address to mail to.

emailCC is the email address to CC.

emailSub is the subject of the email.

emailBody is the email body.

We call window.open with ‘mailto:${emailTo}?cc=${emailCC}&subject=${emailSub}&body=${emailBody}‘ as the first argument to open that URL.

The 2nd argument is '_self' so it won’t open a new tab.

Now when we run the code, we should see the default email client open up with the receiver’s address, CC address, subject and body filled in.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *