我正在尝试使用Sendgrid的Python API来处理Flask应用中的交易电子邮件。
当我启动localhost服务器时,当我完成邀请表单并尝试连接sendgrid API时,我收到401错误,我无法理解原因。
我从sendgrid.env文件导入sendgrid API密钥。
应用的初始化:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import sendgrid
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://unible:test@localhost/unible'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY'] = '\xea5\x1b.S3ME\x86\x8bP/\x86T\xca\x8f\xf4S\xe2h\x9c\xe5\xc6h'
app.config['WTF_CSRF_ENABLED'] = True
app.config['DAYS_TIL_INVITES_EXPIRE'] = 28
db = SQLAlchemy(app)
sendgrid = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
import unible.routes
路由文件:
然后将sendgrid对象导入到我的路径文件中以创建和发送邮件。
from unible import app, sendgrid
from flask import render_template, request, redirect, url_for, abort, flash
from unible.models.invite import Invite
from .forms.InviteForm import InviteForm
from sendgrid.helpers.mail import *
import urllib
@app.route('/account/invites/new', methods=['GET','POST'])
def new_invites():
form = InviteForm()
if request.method == 'GET':
return render_template('invite_form.html', form=form)
if request.method == 'POST':
invite_from = 1 # for testing only, will be replaced by session user id
if form.validate_on_submit():
invite_for = form.email.data.lower()
invite = Invite(invite_from, invite_for)
from_email = Email("test@example.com")
subject = "Hello World from the SendGrid Python Library!"
to_email = Email("test@example.com")
content = Content("text/plain", "Hello, Email!")
msg = Mail(from_email, subject, to_email, content)
try:
response = sendgrid.client.mail.send.post(request_body=msg.get())
print(response.status_code)
print(response.body)
print(response.headers)
except urllib.error.HTTPError as e:
print(e.read())
flash('An invite email was sent to %s' % invite_for)
return redirect(url_for('new_invites'))
else:
return redirect(url_for('new_invites'))
我得到的错误是:
b'{"errors":[{"message":"The provided authorization grant is invalid, expired, or revoked","field":null,"help":null}]}'
然而,当我在服务器外部运行相同的sample code from here时,它可以正常运行并发送?