adonisjs / mail

AdonisJS Email Provider
MIT License
104 stars 34 forks source link

Mail is not sent from an Ace command #62

Closed dimensi0n closed 3 years ago

dimensi0n commented 3 years ago

Package version

5.2.3

Node.js and npm version

Node.js: v14.16.1 Npm: 6.14.12

Sample Code (to reproduce the issue)

import { BaseCommand } from '@adonisjs/core/build/standalone'
import Mail from '@ioc:Adonis/Addons/Mail'

export default class SendMail extends BaseCommand {

    /**
     * Command Name is used to run the command
     */
  public static commandName = 'send:mail'

    /**
     * Command Name is displayed in the "help" output
     */
  public static description = ''

  public static settings = {
    loadApp: true,
  }

  public async run () {
    this.logger.info('Hello world!')
    await Mail.sendLater((message) => {
     try {
          await Mail.sendLater((message) => {
            message
              .from('info@vaillance-emploi.fr')
              .to('interne@vaillance-emploi.fr')
              .subject('Votre offre arrive à expiration : ')
              .text('Hello World')
          })
        } catch(error) {
          console.log(error)
        }
  }
}
dimensi0n commented 3 years ago

I get no errors, but the mail si not sent (I use mailtrap but it works when I send one throug an HTTP Controller). And the offer title is correctly printed on my console.

dimensi0n commented 3 years ago

Someone helped me with this. I had to replace sendLater with send in order to make it work. 👍🏻

justDare commented 1 year ago

Does anyone know why this error occurs with sendLater?

RomainLanz commented 1 year ago

Does anyone know why this error occurs with sendLater?

The sendLater command implies that your mail will be queued in memory and sent later. An Ace command is a short-lived script. The command ends and therefore cleans the process memory before the mail is sent.

There's no reason to use sendLater in an Ace command since it is not dealing with HTTP.

From the documentation:

This ensures that the email is sent in the background and doesn't block the ongoing HTTP request