dword-design / nuxt-mail

Adds email sending capability to a Nuxt.js app. Adds a server route, an injected variable, and uses nodemailer to send emails.
Other
247 stars 18 forks source link

How to use/import in /server/api ? #249

Closed Yves852 closed 2 months ago

Yves852 commented 2 months ago

Hello.

I'm trying to use nuxt-mail server-side with Nuxt but I can't figure out how to import it . Working as expected in client but I would prefer avoid it. Is the project allowing it?

Here is my basic test api:

// server/api/test-mail.js

// import { useMail } from "#imports"
// import useEmail from 'nuxt-mail'
import { useEmail } from 'nuxt-mail'

export default defineEventHandler(async (event) => {
  const mail = useMail()
  // const body: any = await readBody(event)
  // sanitize sanitize sanitize sanitize sanitize sanitize sanitize
  console.log('Test email')
  try {
      mail.send({
        config: 'contact',
        from: 'John Doe',
        subject: 'Test nuxt-mail',
        text: 'This is an incredible test message',
      })
  }
  catch(e) {
    console.error(e)  // [nuxt] [request error] [unhandled] [500] useMail is not defined
    throw createError({
      statusCode: 500,
    })
  }
})
// Client side
<script lang="ts" setup>
const { error, execute, status } = await useFetch((): string => '/api/test-mail', {
  immediate: false,
})

// Works
/*
const mail = useMail()
function send() {
  try {
    mail.send({
      from: 'John Doe',
      subject: 'Test nuxt-mail',
      text: 'This is an incredible test message',
    })
  }
  catch (e) {
    console.error(e)
  }
}
*/
</script>

<template>
  <div>
    <button @click="execute">
      Send email
    </button>
    <div>{{ status }}</div>
    <div v-if="error">
      {{ error }}
    </div>
  </div>
</template>

Thanks.

Yves852 commented 2 months ago

Figured out you recommend Nodemailer for server side in pending PR https://github.com/dword-design/nuxt-mail/pull/112.

Closing issue.