我试着在网上和Stackoverflow上搜索了很长时间,但似乎找不到我需要的答案。
我正在构建一个Python程序,其中用户输入一个ID,然后它试图将其匹配到CSV文件中的一行,如果成功,将从匹配该ID的数据库发送某些详细信息(电子邮件地址存储在CSV文件中)。在这个阶段,我无法将所有信息保存在一个地方(例如数据库),因为我无法控制该设置。
下面是请求用户输入并从数据库中"获取"准备好的信息并启动电子邮件安全连接的代码:
cursor=conn.cursor()
retailer_id = int(input("Enter Retailer ID: "))
cursor.execute("""SELECT Retailer, Retailer_Name, Account_ID, Password from Retailers
where Retailer = ? """, (retailer_id))
users = cursor.fetchone()
try:
users.Account_ID == retailer_id
print("ID exists!")
print(users.Account_ID)
except Exception as e3:
print(e3)
print("No retailers with this ID exists!")
raise
print(users.Retailer, users.Retailer_Name, users.Account_ID, users.Password)
# Create a secure connection with Gmail’s SMTP server, using the SMTP_SSL() of smtplib to
initiate a TLS-encrypted connection
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "example@example.com"
print("Would you like to send emails out to contacts?")
password = input("Type your password and press enter: ")
下面是代码读取CSV和包括一些错误处理:
try:
with open("contacts.csv") as file: # Sending Multiple Personalized Emails using a CSV
file
reader = csv.reader(file)
next(reader) # Skip header row
missing = []
for Retailer, Retailer_Name, Parent_Retailer, Email in reader:
valid = True
if not Retailer.strip():
missing.append("Retailer " + Retailer + " has Retailer ID missing!")
valid = False
if not Retailer_Name.strip():
missing.append("Retailer " + Retailer + " has Retailer name missing!")
valid = False
if not Parent_Retailer.strip():
missing.append("Retailer " + Retailer + " has Parent name missing!")
valid = False
if not Email.strip():
missing.append("Retailer " + Retailer + " has Email missing!")
valid = False
if Retailer is not retailer_id:
missing.append("IDs don't match!")
valid = False
if valid:
server.sendmail(
sender_email,
Email,
message.as_string().format(
Retailer=Retailer,
Retailer_Name=Retailer_Name,
Parent_Retailer=Parent_Retailer,
Email=Email,
previous_month=previous_month,
year=year,
retailer_id=retailer_id),
)
print(missing)
print("Emails sent!")
except SMTPException as e2:
print(e2)
except Exception as e:
print("Emails not sent!")
print(e)
示例CSV文件如下:
Retailer | Retailer_Name | Parent_Retailer | ID 1 | 零售商名称1 | 1400 | example1@example.com |
---|---|---|---|
ID 2 | 零售商名称2 | 1400 | example2@example.com |
ID 3 | 零售商名称3 | 1400 | example3@example.com | ID/td> | 零售商名称4 | 1400 | example4@example.com |
ID 5 | 零售商名称5 | 1400 | example5@example.com |
ID 6 | 零售商名称6 | 1400 | example6@example.com |
零售商是否属于int
类型?
似乎您正在比较string
与int
,这将始终返回为False
->不触发。
解决方案是将字符串强制转换为intint(Retailer)
或使用QUOTE_NONNUMERIC
引用,如下面注释中提到的文档