如何使用Angular5使用SendGrid发送邮件?

时间:2019-06-17 22:28:59

标签: angular5 sendgrid

我正在使用@ sendgird / mail模块发送邮件,但无法发送邮件

我已经尝试过sendGrid API(nodeJs示例),但仍然无法从sendgrid发送邮件

从“ @ sendgrid / mail”中导入*作为SendGridPost; SendGridPost.setApiKey(“ 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”);

sendEmail(){

const msg = {
  to: 'examplemail@gmail.com',
  from: 'examplemail@gmail.com',
  subject: 'Hello world',
  text: 'Hello plain world!',
  html: '<p>Hello HTML world!</p>',
  method: "POST",
  hostname: "api.sendgrid.com",
  port: null,
  path: "/v3/mail/send",
  headers: {
    /* "Access-Control-Allow-Headers": "Authorization, Content-Type, On-behalf-of, x-sg-elas-acl",
    "Access-Control-Allow-Methods": "POST",
    "Access-Control-Allow-Origin": "http://127.0.0.1:8080/",
    //"Access-Control-Allow-Origin": "https://sendgrid.api-docs.io", */
    "Content-Type": "application/json",
    "Authorization": "Bearer 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"
  }
};

SendGridPost.send(msg).then(()=>console.log('sent an email successfully!')).catch(err=>console.log(err));

}

预期: 我会在给定的邮件ID中收到表单SendGrid

1 个答案:

答案 0 :(得分:0)

I replaced configURL for localhost for testing because with committed URL I was getting CROS issue but now its working fine for me

submitEmail()
  {
    let configURL = "https://7vxhbapjzzhmypgyk.stoplight-proxy.io/v3/mail/send";
    //let configURL = "https://api.sendgrid.com/v3/mail/send";

    let jsonPayload = JSON.stringify({
      "personalizations": [
        {
          "to": [
            {
              "email": "examplemail@gmail.com",
              "name": "Balwant Mahara"
            }
          ],
          "subject": this.subject
        }
      ],
      "from": {
        "email": "maharabalwant@gmail.com",
        "name": "Balw Mahara"
      },
      "subject": this.subject,
      "content":[{
        "type": "text/plain",
        "value": "Text Message without html tags"
      },
      {
        "type": "text/html",
        "value": "<body><p>Text Message with html tags</p><body>"
      }
      ]
    });

    let headers = new Headers({
                                "content-type": "application/json",
                                "Authorization": "Bearer YOUR_API_KEY"
                              });

    let options = new RequestOptions({ headers: headers });

    this.http.post(configURL, jsonPayload, options)
    .subscribe(response => {
      console.log("Mail send sucessfully",response);
    },err=>{
      console.log("Mail send Error",err);
    });
   }