如何使用http请求在nodejs服务器代码中将文件发送至HTML格式的邮件? [英] How can I send a file to mail in html form using http request in nodejs server code?

查看:125
本文介绍了如何使用http请求在nodejs服务器代码中将文件发送至HTML格式的邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所做的是当节点服务器运行一个用户可以输入1或2或任何其他数字。如果用户键入1,那么我将打印一条消息作为响应。当用户输入2时,我将显示一个选择文件按钮该用户可以发送带有文件的电子邮件。当用户输入除这两个数字以外的其他号码时,我将显示一条响应消息。实际上,当用户输入2时,我可以发送邮件。现在,我想在用户输入2时发送文件。手动附加文件就像从系统中读取文件一样,我已经完成了。但是我想用http request发送。我在这一点上是struct。所以我该如何解决这个问题。任何帮助将不胜感激。

What I am doing is when node server runs a user can type 1 or 2 or any other number.If user types 1 then I will print a message in response.When user types 2 then I will display a choose file button so that user can send an email with a file.When user enters other than these two numbers I will display a response message.Actually I am able to send a mail when user enters 2.Now I want to send a file when user enters 2.Attaching file manually like reading file from system this I already done.But I want to send with http request.I was struct at this point.So how can I solve this issue.Any help will be appreciated.

以下是我的HTML代码,即samplereal.html

And here is my HTML code i.e, samplereal.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#myForm").hide();
    $("#sub").click(function(){
    if($("#myinp").val() == 1 ) {
        $("#myForm").hide();
        $("#new").text("Email sent without attachment");
        } 
        else if ($("#myinp").val() == 2) {
        $("#myForm").show();
        $("#new").text("");
        }
        else {
        $("#myForm").hide();
        $("#new").text("Email Cannot be send");
        }
    });
});
</script>
</head>
<body>

<input type="number" id="myinp" placeholder="enter 1 or 2"/>
<button id="sub">Send Mail</button>
<form id="myForm" action="/sendForm" method="post" enctype="multipart/form-data">
<input type="file" name="order" value="2" > 
<label > Select a file to upload </label>
<input type="submit" value="Submit">
</form>
<div id="new"></div>
</body>
</html>

这里是我的服务器代码

var request = require('request');
var qs = require('querystring');
var multiparty = require('multiparty');
var util = require('util');
var http = require('http');
var fs = require('fs');
const nodemailer = require('nodemailer');
const xoauth2 = require('xoauth2');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    type: 'OAuth2',
    user: 'SenderMail@gmail.com',
    clientId: 'ClienId from google console developers website',
    clientSecret: 'clientSecret from google console developers website ',
    refreshToken: 'RefreshToken from Oauth2 Playground website',
    accessToken: 'accessToken from Oauth2 Playground website'
  },
});

const server = http.createServer((req, res) => {
  if (req.url === '/sendForm' && req.method === 'POST') {
    var body = "";
    req.on('data', function (chunk) {
      body += chunk;
    });
    req.on('end', function () {
      var mailOptions = {
        from: ' <sendermail@gmail.com>',
        to: 'Receivermail@gmail.com',
        subject: 'Sample mail',
        text: 'Hello !!!!!!!!!!!!!',
      };
      transporter.sendMail(mailOptions, function (err, res) {
        if (err) {
          console.log('Error');
        }
        else {
          console.log('Email Sent');
        }
      });
      res.end("successfully submitted");
    });
  }

  fs.readFile("./switchreal.html", (err, data) => {

    res.writeHead(200, { 'content-type': 'text/html', 'Content-Length': data.length });
    res.end(data);
  });

}).listen(3000, function () {
  console.log("Server Listening on 3000");
});


推荐答案

const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    type: 'OAuth2',
    user: 'SenderMail@gmail.com',
    clientId: 'ClienId from google console developers website',
    clientSecret: 'clientSecret from google console developers website ',
    refreshToken: 'RefreshToken from Oauth2 Playground website',
    accessToken: 'accessToken from Oauth2 Playground website'
  },
});





以下代码解决了我的问题:发送.pdf文件

The below code solved my issue for sending the .pdf files




var mailOptions = {
        from: ' <sendermail@gmail.com>',
        to: 'Receivermail@gmail.com',
        subject: 'Sample mail',
        text: 'Hello !!!!!!!!!!!!!',
            attachments: [{
            // stream as an attachment
        filename: 'text4.txt',//your file name with proper extention
        content: fs.createReadStream('file.txt')                           
         }]
      };

关于添加文件附件的Nodemailer官方文档

希望这对您有用

使用nodemailer通过邮件发送pdf文件的简单代码
https://github.com/Muthukumars1994/sow_app/blob/master/controller.js

Mysimple code which send's the pdf file through mail using nodemailer https://github.com/Muthukumars1994/sow_app/blob/master/controller.js

这篇关于如何使用http请求在nodejs服务器代码中将文件发送至HTML格式的邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆