繁体   English   中英

如何通过 sendgrid - 节点发送邮件

[英]How to send mail via sendgrid - node

我想使用 nextjs 应用程序通过 SendGrid 发送 email,因为它具有无服务器功能。 我通过 SendGrid 演示发送我的第一个 email,现在我想从我的表单发送一个日期。

表单.js

import React, {useState} from 'react';
import { useForm } from 'react-hook-form';

import {
    Row,
    Col,
    Container,
    Form,
    FormGroup,
    Input,
    Button,
  } from "reactstrap";

function Form() {
    const [hasSuccessfullySentMail, setHasSuccessfullySentMail] = useState(false);
    const [hasErrored, setHasErrored] = useState(false);
    const { register, handleSubmit, formState } = useForm();
    const { isSubmitSuccessful, isSubmitting, isSubmitted, errors } = formState;
  
    async function onSubmit(payload) {
      try {
        const res = await fetch('/api/sendEmail', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ subject: 'Email from contact form', ...payload }),
        });
  
        if (res.status !== 204) {
          setHasErrored(true);
        }
      } catch {
        setHasErrored(true);
        return;
      }
  
      setHasSuccessfullySentMail(true);
    }
  
    const isSent = isSubmitSuccessful && isSubmitted;
    const isDisabled = isSubmitting || isSent;
    const isSubmitDisabled = Object.keys(errors).length > 0 || isDisabled;


  return (
<>
<Form onSubmit={handleSubmit(onSubmit)}>

                      <Row>
                        <Col lg="6">
                          <FormGroup className="m-t-15">
                            <Input type="text" placeholder="Wpisz swoje imię" id="name" disabled={isDisabled} {...register('name', { required: true })} />
                          </FormGroup>
                        </Col>
                        <Col lg="6">
                          <FormGroup className="m-t-15">
                            <Input type="text" placeholder="Twój Email" id="email" disabled={isDisabled} {...register('email', { required: true })} />
                          </FormGroup>
                        </Col>
                        <Col lg="12">
                          <FormGroup className="m-t-15">
                            <Input
                              as="textarea"
                              placeholder="Wpisz swoją wiadomość..."
                              id="description"
                              disabled={isDisabled}
                              {...register('description', { required: true })}
                            />
                          </FormGroup>
                        </Col>
                        <Col lg="12">
                          <Button
                            type="submit" disabled={isSubmitDisabled}
                            className="btn btn-danger-gradiant m-t-20 btn-arrow"
                          >
                            <span>
                              {" "}
                              Wyślij <i className="ti-arrow-right"></i>
                            </span>
                          </Button>
                        </Col>
                      </Row>
                    </Form>
</>  )
}

export default Form

问题是在我的控制台中我没有看到任何标头标签。 我在里面查看 Safari > 开发者工具 >.network。 当我使用 Mailchimp 时,我可以注意到某些东西在 1 秒内作为 post-json 发送。 查看控制台,我收到消息说有东西正在发送,但在 40 秒后显示为 web pack-hmr。 我认为这是不同的。

在 sendMail.js 中

require('dotenv').config(sendgrid.env)
require('dotenv').config(sendgrid)

import sendgrid from '@sendgrid/mail';
    
sendgrid.setApiKey(process.env.SENDGRID_API_KEY);
    
export default async (req, res) => {
  const body = JSON.parse(req.body);
  const message = `
  Name: ${body.name}\r\n
  Email: ${body.email}\r\n
  Message: ${body.message}
  `;
  
  const data = {
    to: 'ks@gmail.com',
    from: 'biuro@ase.com',
    subject: 'wiadomosc od klienta',
    text: message,
    html: message.replace(/\r\n/g, '<br>')
  };
  
  console.log(data)

    sendgrid.send(data);

  
    return res.status(200).json({ status: 'Ok' });
};

从技术上讲,这里肯定有一些错误,但 SendGrid 的安装和配置都很好。 所以我只需要更改这段代码。

我最近使用了 SendGrid,因为它是一个外部解析器 API 我在 next.js 的 API 部分做了这个并且工作正常。

// api/mail
import { news_letter_template } from "../../../util/email_templates";
 const sendGrid = require("@sendgrid/mail");
  sendGrid.setApiKey(process.env.NEXT_PUBLIC_SENDGRID_KEY);
  // add this before handler!
  export const config = {
    api: {
       externalResolver: true,
    },
  };
export default function handler(req, res) {
 const body = JSON.parse(req.body);
  console.log('request came => ',body);
  const msg = news_letter_template(body.email);
  sendGrid
   .send(msg)
   .then(() => {
      return res.status(200).json({ send: true });
   })
   .catch((err) => {
     return res.status(400).json({ send: false });
   });
 }

externalResolver设置为true使我的代码正常工作。

//utils/email_templates
const SENDER_EMAIL =
 process.env.NEXT_PUBLIC_SENDER_EMAIL || "Support@weblog.com";
 const weblog_social = {
 insta: "https://www.instagram.com/weblog",
 fb: "https://www.facebook.com/weblog",
 linkedIn: "https://www.linkedin.com/company/weblog",
};

const news_letter_template = (reciverEmail) => {
 const msg = {
    to: reciverEmail,
    from: SENDER_EMAIL,
    subject: "newsletter",
    html: `<p>Dear subscriber,</p><p>Thanks for signing up for  
    newsletter!</p>
    <p> looking forward to hearing from you. </p>
       <p><a href="${weblog_social.insta}">Instagram</a></p>
      <p><a href="${weblog_social.fb}">Facebook</a></p>
        <p><a href="${weblog_social.linkedIn}">LinkedIn</a></p>
      `,
      };
       return msg;
     };

    export { news_letter_template };

我有我的第一个问题的答案。 我的 SendGrid 将日期发布到 api/contact,但有些东西无法正常工作。

import { useState } from 'react'
import {
    Row,
    Col,
    Container,
    Form,
    FormGroup,
    Input,
    Button,
  } from "reactstrap";

function Form() {    
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [message, setMessage] = useState('')
    const [submitted, setSubmitted] = useState(false)
    const [status, setStatus] = useState('')
    
    async function handleOnSubmit(e) {
        e.preventDefault();
        const formData = {
            name,
            email,
            message
        }
        console.log("przesylam dane");
        
        setSubmitted(true)
        
        fetch('/api/contact', {
            method: 'POST',
     
            body: JSON.stringify(formData)
        }).then((res) => {
            if (res.status === 200) {
                console.log("czyszcze pola")
                setSubmitted(false)
                setName('')
                setEmail('')
                setMessage('')
                setStatus('success')
            }
            else {
                console.log("pokazuej blad")
                setStatus('error')
            }
        }) 
    }
    
    return (<>
<Form action='submit' method='POST' onSubmit={handleOnSubmit}>
<Row>
<Col lg="6">
        <div id="name" isRequired className="m-t-15">
            <Input             style={{width: "100%"}}
placeholder="Wpisz swoje imię" type="text" value={name} onChange={(e) => { setName(e.target.value) }} />
        </div>
        </Col>
        <Col lg="6">
        <div id="email" isRequired className="m-t-15">
            <Input             style={{width: "100%"}}

placeholder="Wpisz swój adres email"  type="email" value={email} onChange={(e) => { setEmail(e.target.value) }} />
        </div>
       </Col>
       <Col lg="12">
        <div id="text" isRequired className="m-t-15"> 
        <Input
                              as="textarea"            style={{width: "100%"}}
                placeholder="Wpisz swoją wiadomość.."
                value={message}
                onChange={(e) => { setMessage(e.target.value) }}
            />
        </div>
     </Col>
     <Col lg="12">

        <Button type="submit"
            isLoading={submitted}
            loadingText="Submitting"
            className="btn btn-danger-gradiant m-t-20 btn-arrow"
            style={{width: "200px"}}

        >
         {" "}
                              Wyślij <i className="ti-arrow-right"></i>        </Button>
    </Col>
    </Row>
    {status === "success" ? <span style={{color: "green"}}>wiadomość przesłana</span> : ""}
    {status === "error"  ? <span style={{color: "red"}}>wiadomość nie została wysłana</span> : "" }
    </Form>
</>    )
}
    
export default Form

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM