要在变量中查询股票结果并发送电子邮件,您需要完成以下几个步骤:
以下是一个简单的示例,展示如何使用Python查询股票数据并通过SMTP发送电子邮件。
pip install requests
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 股票查询API(示例)
STOCK_API_URL = "https://api.example.com/stock"
API_KEY = "your_api_key"
# 邮件配置
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
SMTP_USERNAME = 'your_email@gmail.com'
SMTP_PASSWORD = 'your_email_password'
TO_EMAIL = 'recipient@example.com'
def get_stock_data(symbol):
headers = {
'Authorization': f'Bearer {API_KEY}'
}
params = {
'symbol': symbol
}
response = requests.get(STOCK_API_URL, headers=headers, params=params)
if response.status_code == 200:
return response.json()
else:
raise Exception("Failed to fetch stock data")
def send_email(subject, body):
msg = MIMEMultipart()
msg['From'] = SMTP_USERNAME
msg['To'] = TO_EMAIL
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(SMTP_USERNAME, SMTP_PASSWORD)
text = msg.as_string()
server.sendmail(SMTP_USERNAME, TO_EMAIL, text)
server.quit()
# 主程序
if __name__ == "__main__":
stock_symbol = 'AAPL' # 股票代码
try:
stock_data = get_stock_data(stock_symbol)
email_subject = f"Stock Update for {stock_symbol}"
email_body = f"The current price of {stock_symbol} is ${stock_data['price']}"
send_email(email_subject, email_body)
print("Email sent successfully!")
except Exception as e:
print(f"An error occurred: {e}")
通过上述步骤和代码示例,您可以实现从查询股票数据到发送电子邮件的整个流程。
领取专属 10元无门槛券
手把手带您无忧上云