【发布时间】:2021-07-22 21:20:29
【问题描述】:
我正在尝试自动向客户发送计费电子邮件并挖掘我设法达到此结果的互联网。该应用程序包括输入电子表格、检查客户的未结费用、保存到字典和发送提醒电子邮件。但是我也想在付款单上添加附件,但我没有成功。我尝试使用 askopenfilename,但它只发送电子邮件中的文件名而不是附件。
下面是代码:
import openpyxl, smtplib, sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
# Opens the spreadsheet and obtains the status of the last payment.
wb = openpyxl.load_workbook('C:/temp/cobranca.xlsx')
sheet = wb['Sheet1']
lastCol = sheet.max_column
# latestMonth = sheet.cell(row=1, column=lastCol).value
# Checks the payment status of each customer.
unpaidMembers = {}
for r in range(2, sheet.max_row + 1):
for c in range(3, lastCol + 1):
payment = sheet.cell(row=r, column=c).value
if payment != 'ok':
client = sheet.cell(row=r, column=1).value
email = sheet.cell(row=r, column=2).value
month = sheet.cell(row=1, column=c).value
unpaidMembers[client] = email
print('Row:', r, 'Column:', c, 'Client:', client, 'Email:', email, 'Month:', month)
# Log in to your email account.
for client, email, in unpaidMembers.items():
body = "client: %s | month: %s" % (client, month)
print('sending email to %s...' % (email))
# create message object instance
msg = MIMEMultipart()
# setup the parameters of the message
password = "password"
msg['From'] = "email@email.com"
msg['To'] = email
msg['Subject'] = "%s - Open honorary." % (client)
# add in the message body
msg.attach(MIMEText(body))
msg.attach(MIMEText(askopenfilename()))
# create server
server = smtplib.SMTP('mail.omnia.net.br: 587')
server.starttls()
# Login Credentials for sending the mail
server.login(msg['From'], password)
# send the message via the server.
server.sendmail(msg['From'], email, msg.as_string())
server.quit()
messagebox.showinfo("System Message", "Reminders sent successfully.")
print("successfully sent email to %s:" % (email))
使用的电子表格模型:https://prnt.sc/1297huw
【问题讨论】:
-
请看看这是否有帮助send an email with xls as attachment
-
这可能是显而易见的,但电子表格不是文本。你应该做
msg.attach(email.mime.application.MIMEApplication(filecontents))。 -
我觉得我表达得很糟糕,我唯一需要的是能够附加一个文件,只有当他们想在各自的机器上测试代码时,我才会将模板放入电子表格中。