Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React open mailto E-Mail client onClick with body from textarea

Tags:

reactjs

mailto

This sounds like it must have been asked before but I could only find how to do this in react native but I could not find how it's done in normal react for web. Preferably not with an a tag or Link tag that needs to be styled.

Here some code to illustrate what I want to do:

const onClickMailtoHandler = () => {
    //TODO: open default e-mail client e.g. via mailto link with text from (state) variable as body
}

<Button onClick={onClickMailtoHandler}>Send E-Mail</Button>

Here is how to do a mailto link in HTML:

<a href="mailto:[email protected]?body=My custom mail body">E-Mail to Max Mustermann</a>
like image 354
CodingYourLife Avatar asked Sep 07 '20 18:09

CodingYourLife


People also ask

What is onclick handler in react?

In React, the onClick handler allows you to call a function and perform an action when an element is clicked. onClick is the cornerstone of any React app.

How to create an email form in react with emailjs?

EmailJS offers two methods for doing so: emailjs.sendForm dedicated to webforms as it collected the data from its fields and passes them to the template of your choice Here’s a sample code of a React email form component. Put it to the src/Form.js file in your project.

Is it possible to use SMTP in react JS?

Unfortunately not. React JS apps are run on the client-side (in a browser) and the SMTP server needs to be set up on the server-side. In theory, you could provide your SMTP credentials on the client-side, directly in the code.

How to do a mailto link in HTML?

Here some code to illustrate what I want to do: const onClickMailtoHandler = () => { //TODO: open default e-mail client e.g. via mailto link with text from (state) variable as body } <Button onClick={onClickMailtoHandler}>Send E-Mail</Button> Here is how to do a mailto link in HTML:


Video Answer


2 Answers

I ended up creating a component similar to what @GitGitBoom suggested in the comments.

Here for future Seekers:

import React from "react";
import { Link } from "react-router-dom";

const ButtonMailto = ({ mailto, label }) => {
    return (
        <Link
            to='#'
            onClick={(e) => {
                window.location.href = mailto;
                e.preventDefault();
            }}
        >
            {label}
        </Link>
    );
};

export default ButtonMailto;

Use it like this:

<ButtonMailto label="Write me an E-Mail" mailto="mailto:[email protected]" />
like image 175
CodingYourLife Avatar answered Sep 18 '22 16:09

CodingYourLife


I've used the following method for opening the default mail client when button is clicked:

<button onClick={() => window.location = 'mailto:[email protected]'}>Contact Me</button>
like image 26
Code_Elixer Avatar answered Sep 17 '22 16:09

Code_Elixer