我的网站职业页面,用户需要发送其个人资料,然后在单击“提交”按钮时,个人资料(doc或pdf)需要作为电子邮件的附件发送。我正在使用Angular6,NodeJs,Express和Nodemailer来发送电子邮件的技术。
这是我对HTML代码(careers.html)的信赖,
<form (ngSubmit)="sendData()" >
<textarea [(ngModel)]="user.message"></textarea>
<input type="file" (change)="userProfile($event)" >
<small>Upload .docx or pdf file</small>
<button >Submit</button>
</form>
一些ts代码(careers.ts),
user = {
message: '',
fileContent :''
};
userProfile(event: any) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.user.fileContent = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
sendData() {
this.careersService.sendWithAttachment(this.user);
}
这是服务类(service.ts)
sendWithAttachment(userData) {
this.http.post("http://localhost:3000/uploadfile", userData
)
.subscribe(
data => {
console.log("Sent Request is successful ", data);
},
error => {
console.log("Error", error);
}
);
}
最终js文件(app.js)
var mailOptions = {
from: '"User" <mail@gmail.com>', // sender address
to: "mail@mail.com", // list of receivers
subject: "Mail from Careers",
text: text,
html: html, // html body
attachments: [ {
filename: 'profile.pdf',
content: req.body.fileContent,
contentType: 'application/pdf'
}]
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
现在,我可以接收带有附件的电子邮件,但附件为空或已损坏。非常感谢您的帮助。
答案 0 :(得分:0)
您需要将文件上传到服务器上,也许可以通过multer进行上传,然后可以将服务器文件路径传递给Nodemailer函数。
这里有一些代码段供您参考,
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/uploadfile', upload.single('profile'), function (req, res) {
var mailOptions = {
....
attachments: [{
filename: req.file.filename,
path: req.file.path
}]
};
...
})
注意:可以使用Nodemailer中的各种方法进行附加,请参考documentation