Azure桌面版应用SendGrid邮件发送失败问题求助
Azure部署应用SendGrid邮件发送失效排查方案
问题现象
本地笔记本CMD运行应用时,邮件发送功能正常;通过BASH执行测试脚本也能即时发送邮件。但Azure默认域名下的桌面/主屏版本应用,其他功能均正常,唯独SendGrid邮件发送失效。
相关代码如下:
环境变量加载代码
# Load environment variables load_dotenv() SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
邮件发送函数代码
def send_email(to_email, subject, content): message = Mail( from_email='App@My Domain.com', # Use your verified email address to_emails=to_email, subject=subject, plain_text_content=content ) try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) print('Status Code:', response.status_code) print('Body:', response.body.decode('utf-8') if response.body else '') # Ensure body is in readable format print('Headers:', response.headers) except Exception as e: if hasattr(e, 'body'): print('Error Body:', e.body.decode('utf-8')) # Ensure body is in readable format else: print('Error:', str(e))
应用路由代码
print(f"Sending email to xyz@MY Domain.com with subject: {email_subject}") print(f"Email content: {email_content}") try: send_email('xyz@My Domain.com', email_subject, email_content) flash('Project submitted for quote successfully.', 'success') except Exception as e: flash(f'Project submitted for quote successfully, but email notification failed: {e}', 'warning') return redirect(url_for('welcome'))
BASH测试脚本
#!/bin/bash API_KEY="Send Grid Key" EMAIL_TO="xyz@My Domain.com" EMAIL_FROM="app@my domain.com" SUBJECT="Test Email from Azure" CONTENT="This is a test email from your Azure app." curl --request POST \ --url https://api.sendgrid.com/v3/mail/send \ --header "Authorization: Bearer $API_KEY" \ --header "Content-Type: application/json" \ --data '{ "personalizations": [ { "to": [ { "email": "'"$EMAIL_TO"'" } ], "subject": "'"$SUBJECT"'" } ], "from": { "email": "'"$EMAIL_FROM"'" }, "content": [ { "type": "text/plain", "value": "'"$CONTENT"'" } ] }'
排查与解决步骤
1. 环境变量配置验证
- 本地依赖
load_dotenv()读取.env文件,但Azure部署时需在应用服务 -> 配置 -> 应用程序设置中手动配置SENDGRID_API_KEY,确认键名无拼写错误、值无多余空格或格式问题。 - 在
send_email函数开头添加日志,验证是否正确读取到API密钥(仅打印前几位避免泄露):print(f"Loaded SendGrid API key: {SENDGRID_API_KEY[:5]}..." if SENDGRID_API_KEY else "API key not loaded")
2. 发件人邮箱一致性与验证
- 代码中发件人邮箱为
App@My Domain.com,Bash脚本中为app@my domain.com,注意大小写、空格差异。SendGrid要求发件人邮箱必须是已验证的单个邮箱或域名,确认两者均在SendGrid后台完成验证。 - 登录SendGrid控制台,检查发件人验证状态,确保无未通过验证的情况。
3. 应用日志与异常传递修复
- 当前
send_email函数捕获异常后仅打印日志,未重新抛出异常,导致上层路由无法感知发送失败,误以为发送成功。修改函数,在except块末尾添加raise e,让路由代码能捕获并触发警告提示:except Exception as e: if hasattr(e, 'body'): print('Error Body:', e.body.decode('utf-8')) else: print('Error:', str(e)) raise e # 重新抛出异常,让上层路由捕获 - 启用Azure应用服务的日志流(应用服务 -> 监测 -> 日志流),查看邮件发送时的完整错误信息,包括状态码、响应体等。
4. 网络与依赖检查
- 确认Azure应用服务出站流量未被限制,允许访问
https://api.sendgrid.com(可在应用服务 -> 网络 -> 出站流量中查看规则)。 - 检查本地与Azure部署的
sendgrid库版本是否一致,确保requirements.txt中指定了正确的版本号,避免版本差异导致API调用失败。
内容的提问来源于stack exchange,提问作者Brent Brumfield
相关产品推荐
相关产品推荐

