如何以角度6将联系表单详细信息发送到电子邮件?

时间:2019-02-06 05:48:57

标签: node.js angular

我在我的应用程序中使用联系表格。在此,我通过特定的电子邮件ID发送联系表格详细信息。我必须在角度6中完成所有这些操作。我已经使用nodemailer尝试了此操作,但没有获得实现它的正确过程。预先感谢

这是support.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { client, response } from '../../interface'

import { ClientService } from '../../services/client.service'
import { EmailService } from '../../services/email.service'
import { Store } from '@ngrx/store'
import { AppState } from '../../app.state'


@Component({
  selector: 'app-support',
  templateUrl: './support.component.html',
  styleUrls: ['./support.component.css']
})
export class SupportComponent implements OnInit {
  angForm: FormGroup;
  osVersion: {};
  browserName: {};
  browserVersion: {};
  userAgent: {};
  appVersion: {};
  platform: {};
  vendor: {};
  osName : {};
  clientList: client[]

  clientListLoading: boolean = false;
  orgMail: any;
  user: any;


  constructor(public clientService: ClientService,private store: Store<AppState>,
     private fb: FormBuilder,
    private emailService: EmailService) {
    store.select('client').subscribe(clients => this.clientList = clients.filter(cli => cli.enabled == 0))
    this.user = JSON.parse(localStorage.getItem('user'))
    console.log(this.user);
    {
        this.createForm();
      }


   }

   createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      message: ['', Validators.required],
    });
  }
  sendMail(name, email, message) {
    this.emailService.sendEmail(name, email, message).subscribe(success => {

      console.log(success);
    }, error => {
        console.log(error);
    });
  }

  ngOnInit() {
    // this.browser_details();

  }

}

HTML文件:

<form [formGroup]="angForm" novalidate>
<div class="message">
  <h3> Write to us </h3>
</div>
<div class="form__top">
  <div class="form__left">
    <div class="form__group">
      <input class="form__input form__input--name" type="text"   formControlName="name" placeholder="name" #name>
    </div>
    <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
      <div *ngIf="angForm.controls['name'].errors.required">
        Name is required.
      </div>
    </div>
    <div class="form__group">
      <input class="form__input form__input--email" type="email"  formControlName="email" placeholder="email" #email>
    </div>
    <div *ngIf="angForm.controls['email'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
      class="alert alert-danger">
      <div *ngIf="angForm.controls['message'].errors.required">
        message is required.
      </div>
    </div>
  </div>
  <div class="form__right">
    <div class="form__group">
      <textarea class="form__input form__input--textarea" placeholder="Message" formControlName="message"  #message
        rows="3"></textarea>
    </div>
    <div *ngIf="angForm.controls['message'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
      class="alert alert-danger">
      <div *ngIf="angForm.controls['message'].errors.required">
        message is required.
      </div>
    </div>
  </div>
</div>

<div class="form__down">
  <div class="form__group">
    <button (click)="sendMail(name.value, email.value, message.value)" [disabled]="angForm.pristine || angForm.invalid"  class="form__input form__input--submit" name="submit" type="submit" value="SEND MESSAGE">SEND MESSAGE
    </button>
  </div>
</div>

contact.js

const express = require('express');
const router = express.Router();
const request = require('request');
const nodemailer = require('nodemailer');
const cors = require('cors');

router.options('/send', cors()); 
router.get('/send', cors(), (req, res) => {
    const outputData = `
    <p>You have a new contact request</p>
    <h3>Contact Details</h3>
    <ul>  
      <li>Name: ${req.body.name}</li>
      <li>Email: ${req.body.email}</li>
    </ul>
    <h3>Message</h3>
    <p>${req.body.message}</p>
  `;

    let transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: false,
        port: 25,
        auth: {
            user: 'email',
            pass: 'pass'
        },
        tls: {
            rejectUnauthorized: false
        }
    });

    let HelperOptions = {
        from: '"kutomba" <email',
        to: 'email',
        subject: 'Majeni Contact Request',
        text: 'Hello',
        html: outputData
    };



    transporter.sendMail(HelperOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("The message was sent!");
        console.log(info);
    });

});
module.exports = router;

server.js

// server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
// CORS Middleware
app.use(cors());
// Port Number
const port = process.env.PORT || 3000
// Run the app by serving the static files
// in the dist directory
app.use(express.static(path.join(__dirname, '/majeni/dist/majeni')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//routes
const contact = require('./app/components/support/contact');
app.use('/contact', contact);
// If an incoming request uses
// a protocol other than HTTPS,
// redirect that request to the
// same url but with HTTPS
const forceSSL = function () {
  return function (req, res, next) {
    if (req.headers['x-forwarded-proto'] !== 'https') {
      return res.redirect(
        ['https://', req.get('Host'), req.url].join('')
      );
    }
    next();
  }
}

// Instruct the app
// to use the forceSSL
// middleware
// app.use(forceSSL());
app.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  if ('OPTIONS' == req.method) {
    res.sendStatus(200);
    } else {
      next();
    }

});

// For all GET requests, send back index.html
// so that PathLocationStrategy can be used
app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname + '/majeni/dist/majeni/index.html'));
});

// Start Server
app.listen(port, () => {
    console.log('Server started on port '+port);
  });

这是我的email.service.ts

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class EmailService {

   constructor(private http: Http) { }

  sendEmail(name, email, message) {
    const uri = 'http://localhost:4200/support/contact';
    const obj = {
      name: name,
      email: email,
      message: message,
    };
    return this.http.post(uri, obj);
  }
}

1 个答案:

答案 0 :(得分:0)

您不应在contact.js上使用两个端口,并且端口465是安全的端口,请替换:

host: 'smtp.gmail.com', port: 465, secure: false, port: 25, auth: { user: 'email', pass: 'pass' }, tls: { rejectUnauthorized: false }

针对:

host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: email, pass: pass }

在变量email和pass上,您应该设置发送电子邮件的帐户的电子邮件和密码(我建议仅为表单联系人创建一个新的电子邮件帐户,因为默认情况下,gmail帐户不允许客户登录而未设置DMARK e DKIM),并始终确保将这些信息保留在GitHub之类的公共代码存储库之外。

您可以看到我在github上执行的类似代码:https://github.com/anajuliabit/my-website-backend/blob/master/src/Controllers/ContactController.js