使用Angular和Node服务器发送电子邮件可以通过以下步骤实现:
下面是一个示例代码:
在Angular项目中的邮件发送组件:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-mail',
templateUrl: './mail.component.html',
styleUrls: ['./mail.component.css']
})
export class MailComponent {
recipient: string;
subject: string;
content: string;
constructor(private http: HttpClient) { }
sendMail() {
const mailData = {
recipient: this.recipient,
subject: this.subject,
content: this.content
};
this.http.post('/send-mail', mailData).subscribe(
(response) => {
console.log(response);
// 显示发送成功的消息
},
(error) => {
console.error(error);
// 显示发送失败的消息
}
);
}
}
在Node服务器中的路由处理函数:
const express = require('express');
const router = express.Router();
const nodemailer = require('nodemailer');
router.post('/send-mail', (req, res) => {
const { recipient, subject, content } = req.body;
const transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false,
auth: {
user: 'your-email@example.com',
pass: 'your-password'
}
});
const mailOptions = {
from: 'your-email@example.com',
to: recipient,
subject: subject,
text: content
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(error);
res.status(500).send('邮件发送失败');
} else {
console.log('邮件发送成功:', info.response);
res.send('邮件发送成功');
}
});
});
module.exports = router;
请注意,上述示例中的SMTP服务器地址、端口号、发件人邮箱和密码等需要根据实际情况进行配置。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云