将输入值与CSV值匹配,用于发送邮件



我试着在网上和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文件如下:

tbody> <<tr>4 <<tr>
RetailerRetailer_NameParent_RetailerEmail
ID 1零售商名称11400example1@example.com
ID 2零售商名称21400example2@example.com
ID 3零售商名称31400example3@example.com
ID/td>零售商名称41400example4@example.com
ID 5零售商名称51400example5@example.com
ID 6零售商名称61400example6@example.com

零售商是否属于int类型?

似乎您正在比较stringint,这将始终返回为False->不触发。

解决方案是将字符串强制转换为intint(Retailer)或使用QUOTE_NONNUMERIC引用,如下面注释中提到的文档

最新更新