Search code examples
javascriptemailsmtpgmailschedule

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 noti.sitename@gmail.com", //from
        to, //to
        subject, //subject
        body,   //body
        "smtp.gmail.com", //smtp host
        "noti.sitename@gmail.com", //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 ?


Solution

  • 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.