问题描述
为简单起见,我创建了一个Mail.js文件并将其导入到app.js文件中
const sgMail = require('@sendgrid/mail');
const setApiKey = () => sgMail.setApiKey(process.env.SENDGRID_API_KEY);
sendMail = (to,subject,content) => {
return new Promise(async (resolve,reject) => {
try {
setApiKey();
const msg = {
to: [`${to}`],from: 'oabdulazeez70@gmail.com',// Use the email address or domain you verified above
subject: `${subject}`,html: `${content}`,// attachments: [
// {
// content: Buffer.from(fileList.name,'base64'),// filename: `${fileList}`,// type: ['application/pdf','image/png','image/jpg'],// disposition: 'attachment',// },// ],};
const result = await sgMail.send(msg);
resolve(result);
console.log('Message sent!');
} catch (err) {
console.log('Error in sendEmail: ',err.response.body);
reject(err.response.body);
}
});
};
module.exports = sendMail;
在我的app.js中
const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const cors = require('cors');
const path = require('path');
const dotenv = require('dotenv');
const app = express();
const multer = require('multer');
const upload = multer({ dest: './public/uploads/' });
dotenv.config({
path: './config/config.env',});
const sendMail = require('./mail');
// View engine setup
// Static folder
app.use(express.static(path.join(__dirname,'public')));
// Body Parser Middleware
app.use(
bodyParser.urlencoded({
extended: false,})
);
app.use(bodyParser.json());
app.use(cors());
app.get('/',(req,res) => {
res.sendFile(path.join(__dirname,'public','contact.html'));
});
app.post('/send',async (req,res) => {
try {
const { email,content } = req.body;
await sendMail(email,content);
res.json({
message: 'Message Sent!',});
} catch (error) {
res.status(400).json({
message: 'Something went wrong',});
}
console.log(req.body);
});
// Setting PORT from config
const PORT = process.env.PORT || 5000;
app.listen(PORT,() => console.log(`Server Started on ${PORT}`));
在我的前端
const getIds = (id) => {
return document.getElementById(id);
};
// quill rich text editor API
let options = [
[{ header: [1,2,3,4,5,6,false] }],['bold','italic','underline','strike','link','code'],['blockquote','code-block'],[{ list: 'ordered' },{ list: 'bullet' }],[{ script: 'sub' },{ script: 'super' }],[{ indent: '-1' },{ indent: '+1' }],[{ direction: 'rtl' }],['image','video','formula'],[{ align: ['center'] }],];
let quill = new quill('#editor',{
modules: {
toolbar: options,},theme: 'sNow',});
// Grabbing the Form
const form = getIds('form');
let fileList = [];
const fileInput = getIds('file-input');
const toBase64 = (file) =>
new Promise((resolve,reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
fileInput.addEventListener('change',(e) => {
fileList = [];
for (let i = 0; i < fileInput.files.length; i++) {
fileList.push(fileInput.files[i]);
console.log(fileList);
}
});
const sendMail = () => {
const email = getIds('email').value;
const subject = getIds('subject').value;
const myBtn = getIds('btn');
const htmlFormat = quill.root.innerHTML;
const content = (getIds('content').value = htmlFormat);
const data = {
email,content,//fileList
};
myBtn.disabled = true;
axios
.post('/send',data,{
headers: {
'Content-Type': 'application/json',})
.then((res) => {
myBtn.disabled = false;
form.reset();
quill.setContents([{ insert: '\n' }]);
M.toast({ html: 'Email Sent!',classes: '' });
console.log(res);
})
.catch((err) => {
myBtn.disabled = false;
M.toast({ html: `Error: ${err.message}` });
console.log(err);
});
};
form.addEventListener('submit',(e) => {
e.preventDefault();
sendMail();
});
我的表格
<form id="form" enctype="multipart/form-data">
<div>
<div class="input-field">
<input id="email" type="email" required />
<label class="active" for="email">Email Address</label>
</div>
<div class="input-field">
<input id="subject" type="text" required />
<label class="active" for="subject">Subject</label>
</div>
<div class="input-field hide">
<input id="content" type="text" />
<label class="active" for="content"></label>
</div>
</div>
<div class="w-md">
<div id="toolbar">
<div class="file-field input-field">
<div class="btn btn-small">
<span><i class="small material-icons">attach_file</i></span>
<input type="file" id="file-input" multiple />
</div>
<div class="file-path-wrapper">
<input class="file-path" type="text">
</div>
</div>
</div>
<div id="editor"></div>
</div>
<div class="mt-2 mb-2 center">
<button class="btn waves-effect waves-light btn-small" id="btn" type="submit">Submit
<i class="small material-icons right">send</i>
</button>
</div>
</form>
我想从前端添加附件并发送(附件可以接受pdf,doc,zip,png,jpg等文件)。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)