最近用smtplib发送邮件验证码,遇到了玄学编码问题
verify_text = "您好,您的验证码是{code}"
def send_email(receiver, verify_code):
try:
message = MIMEText(verify_text.format(code = verify_code), 'html', 'utf-8')
message['From'] = MAIL_USEERNAME
message['To'] = receiver
message['Subject'] = Header("邮件验证码","utf-8")
context = ssl.create_default_context()
print(message.as_string())
with smtplib.SMTP_SSL(MAIL_SERVER, MAIL_PORT, context = context) as server:
server.login(MAIL_USEERNAME,MAIL_PASSWORD)
server.sendmail(MAIL_USEERNAME, receiver, message.as_string())
return 0
except Exception as e:
print("mail error : ", e)
return -1
这个函数直接发送邮件是没问题的,但是放在api里面调用,就会发生
'ascii' codec can't encode characters in position 219-220: ordinal not in range(128)
API的代码如下:
@app.route('/get_mail_verify', methods = ['GET'])
def mail_verify():
email = request.values.get('email',type = str, default = None)
if MyRedis.get(email) != None:
verify_code = MyRedis.get(email)
else:
verify_code = get_verify_code()
MyRedis.set(email, verify_code, REDIS_STAY_TIME)
return_json = {'data':{}}
if send_email(email, verify_code) == -1:
#发送失败,可能是网络问题或者email有误
return_json['code'] = 900
return_json['data']['msg'] = "Email can't use or Network congestion"
return jsonify(return_json)
else:
return_json['code'] = 200
return_json['data']['msg'] = "Get verify code successfully"
return jsonify(return_json)
不知道如何解决,只好放弃中文,写英文邮件,就不会出问题了。