首页 > 解决方案 > 使用 Angular5 前端在 NodeJS 中使用 nodemailer 发送邮件

问题描述

每当我注册用户时,我想从我的 nodejs 服务器发送一封电子邮件。我使用 Angular5 作为前端。它不会返回任何错误,但它也不起作用。就像我的函数根本没有被调用。这是我尝试过的(在此示例中电子邮件不是真实的):

服务器.js

app.post('/sendMails', function(req,res) {

    console.log("WENT INTO SEND MAILS!!!")


    let transporter = nodemailer.createTransport({
        service: 'gmail',
        secure: false,
        port: 25,
        auth: {
            user: 'someemail@gmail.com',
            pass: process.env.MAIL_PASSWORD
        },

        tls: {
            rejectUnauthorized: false
        },

    });

    let HelperOptions = {

        from: '"Babababa" <someemail@gmail.com>',
        to: 'someemail@gmail.com',
        subject: 'Hello world',
        text: 'hey dude'
    };

    transporter.sendMail(HelperOptions, (error, response) => {
        if(error) {
           return console.log(error);
           res.json({error: "API Error"});
        }

        else{
            console.log("The message is sent: " + response.message);
            res.json({response: "sent"})
        }




    })


    });

来自角

UserService.ts(相关部分)

constructor(private http: HttpClient) { }

      sendMail(user: User){
    console.log("sendMail()  was called.")
    return this.http.post("http://localhost:3000/sendMails", user.email);
  }

这在我注册时的注册组件中调用

注册.component.ts

     public signUp(){

    //marks all fields as touched.
    this.fs.markFormGroupTouched(this.registerForm);


    if(this.registerForm.valid) {

      let user: User = this.registerForm.value;
      console.log(user)

      this.userService.createUser(user);
      this.userService.sendMail(user); //<--- only this is relevant for this case.

    }
    else {
      //shows the error messages, for the not valid input fields.
      this.formErrors = this.fs.validateForm(this.registerForm,
      this.formErrors, false)
    }



  }

当我运行此代码时,没有错误。在检查器/客户端控制台窗口中,我看到消息“sendMail() 被调用”。,这意味着它肯定在调用我的服务。但是,我没有收到任何邮件或任何错误

标签: node.jsemailangular5nodemailer

解决方案


内部返回一个可观察的http.post()sendMail()必须订阅这个 observable,否则它不会被执行。

所以registration.component.ts你需要这样的东西:

this.userService.sendMail(user).subscribe(
  response => {
    console.log(response);
  }
);

推荐阅读