我已经在SendGrid上设置了一个账户。我已获得API密钥和Node.js方法。我正在使用React js创建一个Web应用程序,希望通过SendGrid发送电子邮件。但是我无法找到任何解决方案。请用示例来回答我的问题。
我已经在SendGrid上设置了一个账户。我已获得API密钥和Node.js方法。我正在使用React js创建一个Web应用程序,希望通过SendGrid发送电子邮件。但是我无法找到任何解决方案。请用示例来回答我的问题。
使用React是不可能的,因为它是一个前端库,如果您尝试使用React实现,您将会遇到以下错误:
---> 拒绝设置不安全的标头 "User-Agent"
如果您需要设置这些标头,则需要从您的服务器而不是访问者的浏览器发起请求。
因此,从React中无法实现该功能,您需要使用一些后端或Firebase来实现。
有多种解决方案可供选择。
//Form.js
class Form extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('/api/form-submit-url', {
method: 'POST',
body: data,
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<label htmlFor="email">Enter your email</label>
<input id="email" name="email" type="email" />
<label htmlFor="birthdate">Enter your birth date</label>
<input id="birthdate" name="birthdate" type="text" />
<button>Send data!</button>
</form>
);
}
}
//index.js
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: test@example.com',
from: 'test@example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);