npm package: @gulibs/tegg-nodemailer
Description: Nodemailer plugin for Egg.js 4.x - Send emails easily
Author: HectorGu
Latest version: 0.0.4

# @gulibs/tegg-nodemailer

[![NPM version](https://img.shields.io/npm/v/@gulibs/tegg-nodemailer.svg?style=flat-square)](https://npmjs.org/package/@gulibs/tegg-nodemailer)
[![NPM downloads](https://img.shields.io/npm/dm/@gulibs/tegg-nodemailer.svg?style=flat-square)](https://npmjs.org/package/@gulibs/tegg-nodemailer)

Nodemailer plugin for Egg.js 4.x - Send emails easily with SMTP.

## Features

- 📧 Easy email sending with Nodemailer
- ✅ Full TypeScript support
- 🔒 Secure SMTP connections (SSL/TLS)
- 🎯 Access via `app.nodemailer` and `ctx.nodemailer`
- ⚡ Auto-verify SMTP connection on startup

## Requirements

- Node.js >= 22.18.0
- Egg.js >= 4.1.0-beta.35

## Install

### Install Latest Version

```bash
pnpm add @gulibs/tegg-nodemailer
# or
npm i @gulibs/tegg-nodemailer
```

### Install Beta Version

To install the beta version, you must explicitly specify the `@beta` tag:

```bash
pnpm add @gulibs/tegg-nodemailer@beta
# or
npm i @gulibs/tegg-nodemailer@beta
```

**Note**: Using `@latest` or no tag will install the latest stable version, not the beta version.

## Usage

### 1. Enable Plugin

```typescript
// config/plugin.ts
import nodemailerPlugin from '@gulibs/tegg-nodemailer';

export default {
  ...nodemailerPlugin(),
};
```

### 2. Configure SMTP

```typescript
// config/config.default.ts
export default {
  teggNodemailer: {
    client: {
      // SMTP server configuration
      host: 'smtp.gmail.com',
      port: 587,
      secure: false, // true for 465, false for other ports

      // Authentication
      auth: {
        user: 'your-email@gmail.com',
        pass: 'your-app-password', // Use app-specific password for Gmail
      },
    },
  },
};
```

### 3. Send Email

```typescript
// In controller or service
import type { Context } from 'egg';

export default class HomeController {
  async sendEmail(ctx: Context) {
    try {
      const info = await ctx.nodemailer.sendMail({
        from: '"Your App" <noreply@example.com>',
        to: 'recipient@example.com',
        subject: 'Hello from Egg.js',
        text: 'This is a plain text email',
        html: '<b>This is an HTML email</b>',
      });

      ctx.body = {
        success: true,
        messageId: info.messageId,
      };
    } catch (error) {
      ctx.logger.error('Failed to send email:', error);
      ctx.body = {
        success: false,
        error: error.message,
      };
    }
  }
}
```

## Configuration

### Plugin Configuration

```typescript
interface NodemailerConfig {
  /**
   * Nodemailer transporter configuration
   */
  client: NodemailerClientConfig | TransportOptions;

  /**
   * Verify transporter connection on app startup
   * Default: true
   * Set to false to skip verification if SMTP server is slow or unreliable
   */
  verify?: boolean;

  /**
   * Verification timeout in milliseconds
   * Default: 5000 (5 seconds)
   * Set to 0 to disable timeout (not recommended)
   */
  verifyTimeout?: number;
}
```

### Client Configuration

```typescript
interface NodemailerClientConfig {
  /**
   * SMTP server host (e.g., 'smtp.gmail.com')
   */
  host: string;

  /**
   * SMTP server port
   * - 465: Secure SMTP (SSL/TLS)
   * - 587: SMTP with STARTTLS
   * - 25: Standard SMTP (not recommended)
   */
  port: number;

  /**
   * Use secure connection (SSL/TLS)
   * - true: for port 465
   * - false: for port 587 (will upgrade with STARTTLS)
   * Default: auto-detect based on port
   */
  secure?: boolean;

  /**
   * Authentication credentials
   */
  auth: {
    /**
     * SMTP username (usually your email address)
     */
    user: string;
    /**
     * SMTP password or app-specific password
     */
    pass: string;
  };
}
```

### Troubleshooting Connection Issues

If you encounter timeout or connection issues:

**1. Skip verification (quickest fix)**

```typescript
// config/config.default.ts
export default {
  teggNodemailer: {
    client: {
      host: 'smtp.example.com',
      port: 587,
      // ... other config
    },
    verify: false, // Skip verification on startup
  },
};
```

**2. Increase timeout (for slow SMTP servers)**

```typescript
export default {
  teggNodemailer: {
    client: {
      // ... SMTP config
    },
    verify: true,
    verifyTimeout: 10000, // 10 seconds (default is 5 seconds)
  },
};
```

**3. Common issues**
- **"Greeting never received"**: SMTP server is slow or unreachable
  - Solution: Set `verify: false` or increase `verifyTimeout`
- **"Authentication failed"**: Wrong credentials
  - Check username/password
  - For Gmail, use [App Password](https://myaccount.google.com/apppasswords)
- **"Connection timeout"**: Firewall or network issue
  - Check if port is accessible
  - Try different port (587 vs 465)

## Common SMTP Configurations

### Gmail

```typescript
{
  host: 'smtp.gmail.com',
  port: 587,
  secure: false,
  auth: {
    user: 'your-email@gmail.com',
    pass: 'your-app-password', // Generate at https://myaccount.google.com/apppasswords
  },
}
```

### Outlook/Hotmail

```typescript
{
  host: 'smtp-mail.outlook.com',
  port: 587,
  secure: false,
  auth: {
    user: 'your-email@outlook.com',
    pass: 'your-password',
  },
}
```

### QQ Mail

```typescript
{
  host: 'smtp.qq.com',
  port: 465,
  secure: true,
  auth: {
    user: 'your-email@qq.com',
    pass: 'your-authorization-code', // Get from QQ Mail settings
  },
}
```

### 163 Mail

```typescript
{
  host: 'smtp.163.com',
  port: 465,
  secure: true,
  auth: {
    user: 'your-email@163.com',
    pass: 'your-authorization-code', // Get from 163 Mail settings
  },
}
```

## API

### `app.nodemailer` / `ctx.nodemailer`

Nodemailer transporter instance. See [Nodemailer documentation](https://nodemailer.com/) for full API.

#### `sendMail(options)`

Send an email.

```typescript
const info = await ctx.nodemailer.sendMail({
  from: '"Sender Name" <sender@example.com>',
  to: 'recipient@example.com, another@example.com',
  cc: 'cc@example.com',
  bcc: 'bcc@example.com',
  subject: 'Email Subject',
  text: 'Plain text content',
  html: '<p>HTML content</p>',
  attachments: [
    {
      filename: 'file.pdf',
      path: '/path/to/file.pdf',
    },
  ],
});
```

#### `verify()`

Verify SMTP connection.

```typescript
try {
  await app.nodemailer.verify();
  console.log('SMTP connection is ready');
} catch (error) {
  console.error('SMTP connection failed:', error);
}
```

## TypeScript Support

Full TypeScript support with type definitions:

```typescript
import type { 
  Transporter, 
  SendMailOptions, 
  SentMessageInfo 
} from '@gulibs/tegg-nodemailer';

// Or use from nodemailer directly
import type { SendMailOptions } from 'nodemailer';
```

## Troubleshooting

### Gmail "Less secure app access" Error

Gmail requires app-specific passwords. Generate one at:
https://myaccount.google.com/apppasswords

### Connection Timeout

- Check firewall settings
- Verify SMTP host and port
- Ensure network allows SMTP connections

### Authentication Failed

- Double-check username and password
- Use app-specific password for Gmail/Yahoo
- Enable SMTP access in your email provider settings

## License

MIT

## Related

- [Nodemailer](https://nodemailer.com/) - The underlying email library
- [Egg.js](https://www.eggjs.org/) - The Egg.js framework
- [@gulibs/tegg-guard](https://github.com/gulibs/tegg-guard) - Authentication plugin
- [@gulibs/tegg-ali-oss](https://github.com/gulibs/tegg-ali-oss) - OSS plugin