错误ReferenceError:未定义nodemailer

时间:2018-06-03 22:08:01

标签: javascript node.js typescript angular5 nodemailer

我已经添加了tsconfig.app.json" types":[" node"]

我只想使用angular 5 ..

创建一个简单的电子邮件发件人

如果有其他使用google mail API的教程链接,请给我一个链接

继承我的代码

import { Component, OnInit, Input, EventEmitter } from '@angular/core';

declare var nodemailer: any;

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})

export class ContactComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    let transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        type: 'OAuth2', 
        user: 'XXX@gmail.com',
        clientId: 'XXX-XXX.apps.googleusercontent.com',
        clientSecret: 'SY0-XXXX',
        refreshToken: '1/XXX_XXX',
        accessToken: 'ya29.XXX-XXX-XXX-XXX'
      }
    })

    let mailOptions = {
      from: 'FReyes <XXX@gmail.com>',
      to: 'XXX@gmail.com',
      subject: 'Nodemailer test',
      text: 'Hello World!!'
    }

    transporter.sendMail(mailOptions, function (err, res) {
      if(err){
          console.log('Error');
      } else {
          console.log('Email Sent');
      }
    })
  }
}

我正在使用nodemailer 这是我的错误

error preview

1 个答案:

答案 0 :(得分:0)

Nodemailer在服务器端工作。你能做的就是用它制作一个API。

类似的东西:

//服务器端

const express = require('express');
const nodemailer = require('nodemailer');

const app = express();

// Express
app.post('/api/mail', (req, res) => {
    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            type: 'OAuth2', 
            user: 'XXX@gmail.com',
            clientId: 'XXX-XXX.apps.googleusercontent.com',
            clientSecret: 'SY0-XXXX',
            refreshToken: '1/XXX_XXX',
            accessToken: 'ya29.XXX-XXX-XXX-XXX'
        }
    })

    let mailOptions = {
        from: 'FReyes <XXX@gmail.com>',
        to: req.body.to,
        subject: req.body.subject,
        text: req.body.txt
    }

    transporter.sendMail(mailOptions, function (err, res) {
        if(err){
            console.log('Error');
        } else {
            console.log('Email Sent');
        }
    })
});

app.listen(3000);

//客户端

sendMail() {
    const data = {
        to: 'email@mail.com',
        subject: 'Subject',
        txt: 'hello world'
    };

    return this.http.post('/api/mail', data).map((response: Response) =>{
        console.log (response.json());
    })
}