sridhar chary
sridhar chary

Reputation: 31

how to send mail in strapi cms while submit form from frontend

using strapi version4, tried this for send mail, but did not work for me.

https://strapi.io/blog/how-to-create-and-use-sms-and-email-services-in-strapi-1

could you please explain me on how to override create method in strapi cms.

Upvotes: 3

Views: 3437

Answers (1)

jeremy0505h
jeremy0505h

Reputation: 21

You can use Nodemailer or Sendgrid, I'm gonna use Nodemailer in this example but I personally prefer SendGrid.

ssh to your strapi server

  • install nodemailer: npm i @strapi/provider-email-nodemailer

  • choose config folder / plugins.js - you can create it as a new file if you dont have

Copy this:

module.exports = ({ env }) => ({
  // ...
  email: {
    config: {
      provider: 'nodemailer',
      providerOptions: {
        host: env('SMTP_HOST', 'smtp.example.com'),
        port: env('SMTP_PORT', 587),
        auth: {
          user: env('SMTP_USERNAME'),
          pass: env('SMTP_PASSWORD'),
        },
      },
      settings: {
        defaultFrom: '[email protected]',
        defaultReplyTo: '[email protected]',
      },
    },
  },
});
  • inside your project there is an .env file, open it and copy:

    EMAIL_PROVIDER=nodemailer EMAIL_SMTP_HOST=sandbox.smtp.mailtrap.io EMAIL_SMTP_PORT=2525 EMAIL_SMTP_USER=your_mailtrap_user EMAIL_SMTP_PASS=your_mailtrap_password [email protected] [email protected]

Notice I'm using mailtrap here for testing purposes, you can sign up here

  • e-mail testing
  • add an inbox
  • on the right side Integrations choose nodemailer and you'll see the password and user

go back to your strapi project src/api/choose your collection type where you store the data you sent from frontend/content-types

in content-types make a new file called lifecycles.js and copy this:

module.exports = {
  async afterCreate(event) {
    const { result } = event;
    try {
      await strapi.plugins['email'].services.email.send({
        to: '[email protected]',
        from: `[email protected]`,
        subject: `This is a test mail`,
        html: `Hello world ${result.name}` //<- (you'll need a name field in strapi collection type to display this data)
      });
    } catch (err) {
      console.log(err);
    }
  },
};

Now each time there is a new post from your frontend to strapi you'll receive an email to your mailtrap account, later you can use a real SMTP server instead of mailtrap. You can also make a test in strapi admin panel Settings/E-mail plugin - Configuration

plugins.js,lifecycles.js .env

Hope it helps!

Upvotes: 2

Related Questions