Ali H
Ali H

Reputation: 923

How to send scheduled email in javascript?

I'm using SMTPJS to send emails by Gmail SMTP. Here my simple work code:

<script src="https://smtpjs.com/v2/smtp.js"></script>

sendEmail(to, subject, body){ 
    Email.send(
        "SITENAME [email protected]", //from
        to, //to
        subject, //subject
        body,   //body
        "smtp.gmail.com", //smtp host
        "[email protected]", //username account
        "Noti-Password",    //password account
        message=>{
            alert("sent");
        }
    )
}

What I need to do is sending an email that should be sent by date. For example after 2 weeks or after 30 days. So is that possible by adding some lines or doing an other way ?

Upvotes: 2

Views: 3612

Answers (2)

Maurici Abad
Maurici Abad

Reputation: 1718

You can't do this in the Front End because JavaScript on the browser is only executed while the site is opened.

To do it you need a server to run a code every X time, that's a cron. That code can be written in languages such as Python, JavaScript (Node.js) o PHP.

If you can host that on a website you probably can also run PHP so I recommend you to use PHP. This is how you would do it:

  1. In your HTML use a Form to send the content of the email via POST to a PHP file.

  2. Upload a PHP file that reads the POST parameters and saves a file (for example a JSON) that contains, for each email: the timestamp in which should be sent and the email content.

  3. Upload a PHP file that reads the "pending emails to send" file and sends the emails that have a past timestamp and removes that mail from the file.

  4. Set up a cron that runs the second PHP file every one day at 8am.

Upvotes: 0

Vishal choudhary
Vishal choudhary

Reputation: 315

I think it's not possible with only JavaScript For this you need to open your browser for that specific time it can be manage from the server side but as far my concern from client side it can be done with extension only that must be embedded in client browser. You can you use background or cantent script to send the message at the particular time

Upvotes: 1

Related Questions