我有两个 python 脚本,第一个脚本将本地气象站的数据提取到文本文件中,第二个脚本将文本文件内容插入电子邮件正文中。文件的内容如下面的预期输出所示,但我在“主题”字段中得到“无主题”。我使用了基本电子邮件包https://docs.python.org/3/library/email.examples.html.
第一个脚本:
import urllib.request
import json
import datetime as dt
with urllib.request.urlopen('https://api.weather.gov/gridpoints/RAH/61%2c55/forecast') as url:
data = json.load(url)
iso_date = dt.datetime.fromisoformat(
data['properties']['periods'][0]['endTime'])
utc_date = iso_date.strftime('%b %d, %Y')
time_of_day = data['properties']['periods'][0]['name']
temp = data['properties']['periods'][0]['temperature']
rel_humidity = data['properties']['periods'][0]['relativeHumidity']['value']
sf = data['properties']['periods'][0]['shortForecast']
df = data['properties']['periods'][0]['detailedForecast']
weather_report = (
f"This is a weather report for North Raleigh: \n\nDate of forecast: {utc_date}\nTime of Day: {time_of_day} \nTemperature: {temp} \nRelative Humidity: {rel_humidity} \nShort Forecast: {sf}
\n
Detailed Forecast: {df}")
with open("weather.txt", "w") as outfile:
outfile.write(weather_report)
第二个脚本:
from data import extract_data
import smtplib, os
from email.message import EmailMessage
from dotenv import load_dotenv
_ = load_dotenv()
extract_data()
email_address = os.environ.get("gmail_username")
email_password = os.environ.get("gmail_password")
msg = EmailMessage()
msg['Subject'] = f'Daily Weather Report'
sender_email = email_address
receiver_email = "[email protected]"
password = email_password
with open("weather.txt", "r") as my_file:
file_content = my_file.read()
server=smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, file_content, msg)
server.quit()
这就是我得到的:
(no subject)
[email protected]
Date of forecast: Feb 17, 2024
Time of Day: This Afternoon
Temperature: 51
Relative Humidity: 36
Short Forecast: Partly Sunny
Detailed Forecast: Partly sunny, with a high near 51. Northwest wind 8 to 12 mph.
这是预期的输出:
Daily Weather Report
[email protected]
Date of forecast: Feb 16, 2024
Time of Day: Overnight
Temperature: 42
Relative Humidity: 76
Short Forecast: Partly Cloudy
Detailed Forecast: Partly cloudy, with a low around 42. West wind 2 to 6 mph.
不久前我也遇到了同样的问题...我发现使用 smtplib.SMTP.send_message() 函数而不是 smtplib.SMTP.sendmail() 更容易。您首先必须将所有信息(主题、发件人、收件人和内容)放入邮件本身中。然后使用 send_message() 发送消息。
我复制了您的代码(使用我自己的服务器和凭据),并且收到了一条带有主题的消息。
这是我对你的第二个脚本的建议:
from data import extract_data
import smtplib, os
from email.message import EmailMessage
from dotenv import load_dotenv
_ = load_dotenv()
extract_data()
email_address = os.environ.get("gmail_username")
email_password = os.environ.get("gmail_password")
with open("weather.txt", "r") as my_file:
file_content = my_file.read()
# Part 1: Prepare the message
msg = EmailMessage()
msg['Subject'] = f'Daily Weather Report'
msg.set_content(file_content) # <--- set the content of the message
msg["From"] = sender_email # <--- set the origin address
msg["To"] = receiver_email # <--- set the destination address
# Part 2: Send the message
server=smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(sender_email, password)
server.send_message(msg) # <--- use this function instead
server.quit()
希望它对你有用!