Skip to content

Custom headers not sent when using nodemailer #79

@rmmlopes

Description

@rmmlopes

Package version

7.2.5

Node.js and npm version

16.14.2
8.5.0

Sample Code (to reproduce the issue)

Mail headers do not get sent out if this isn't done.
I'm sure there is a more elegant way of doing this, but this is what got me going

/*

  • @adonisjs/mail
  • (c) Harminder Virk virk@adonisjs.com
  • For the full copyright and license information, please view the LICENSE
  • file that was distributed with this source code.
    */

///

import nodemailer from 'nodemailer'
import {
MessageNode,
SmtpMailResponse,
SmtpDriverContract,
SmtpConfig,
} from '@IOC:Adonis/Addons/Mail'

/**

  • Smtp driver to send email using smtp
    */
    export class SmtpDriver implements SmtpDriverContract {
    private transporter: any

constructor(config: SmtpConfig) {
this.transporter = nodemailer.createTransport(config)
}

/**

  • Send message
    */
    public async send(message: MessageNode): Promise {
    if (!this.transporter) {
    throw new Error('Driver transport has been closed and cannot be used for sending emails')
    }
message.headers = this.convertHeadersToNodemailFormat(message.headers)

return this.transporter.sendMail(message)

}

/**

  • Close transporter connection, helpful when using connections pool
    */
    public async close() {
    this.transporter.close()
    this.transporter = null
    }

/**

  • nodemailer expects an object for headers, Adonis mailer uses an an array of objects
  • headers: [ { 'x-test': 'teststr' }, { 'x-test': '1234' } ] ===>
  • headers: { 'x-test': [ 'teststr', '1234' ] }
    */
    public convertHeadersToNodemailFormat(headers) {
    if (headers) {
    var newHeaders = {}
    for (var header of headers) {
    for (var headerKey in header) {
    if (!newHeaders[headerKey]) {
    newHeaders[headerKey] = []
    }
    if (header[headerKey] instanceof Array) {
    for (var headerListVal of header[headerKey]) {
    newHeaders[headerKey].push(headerListVal)
    }
    } else {
    newHeaders[headerKey].push(header[headerKey])
    }
    }
    }
    return newHeaders
    }
    return headers
    }
    }

BONUS (a sample repo to reproduce the issue)

https://github.com/rmmlopes/mail

Metadata

Metadata

Assignees

Labels

Type: BugThe issue has indentified a bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions