gpt4 book ai didi

python-3.x - 电子邮件未发送excel附件

转载 作者:行者123 更新时间:2023-12-03 08:42:19 25 4
gpt4 key购买 nike

我正在尝试将带有附件的电子邮件发送给存储在csv文件中的各种收件人。我的目的是向收件人发送存储在特定位置的相应附件。

csv看起来像这样

Name,Emails,Firm
Tom,tom@fakedomian.com,Firm1
Dick,dick@fakedomain.com,Firm2
Harry,harry@fakedomain.com,Firm3

在文件夹中,附件看起来像这样
path='C:\\Documents\\Firms'

在该位置,文件将如下所示
Firm1.xlsx
Firm2.xlsx
Firm3.xlsx

以下代码使用csv中的名称和电子邮件在通过文件夹附加相应的excel文件时发送个性化电子邮件。
import email, csv, smtplib, ssl, fnmatch, os, codecs

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import fnmatch

path = 'C:\\Documents\\Firms'
email_html = open('email.html')
body = email_html.read()


from_address = "youremail@domain.com"
password = input("Type your password and press enter: ")

#context = ssl.create_default_context()
with smtplib.SMTP("smtp.office365.com", 587) as server:
server.ehlo()
server.starttls()
server.login(from_address, password)
with open("Firms.csv") as file:
reader = csv.reader(file)
next(reader)
for Name, Email, Firm in reader:
# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = from_address
message["To"] = Email
message["Subject"] = 'Test ' + Name

#Add body to email and excel attachment

message.attach(MIMEText(body, "html"))

for i in os.listdir(path):
if os.path.isfile(os.path.join(path,i)) and Firm in i:
with open(os.path.join(path, i), 'rt', encoding='ISO-8859-1') as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())

encoders.encode_base64(part)

part.add_header(
"Content-Disposition",f"attachment; filename= {Firm}",)

message.attach(part)
text = message.as_string()

# Use server to send email
server.sendmail(from_address, Email, text.format(name=Name))

尽管这会发送电子邮件,但附件不是Excel格式。当我使用encoding ='utf8'时,我将得到以下错误
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 18: character maps to <undefined>

在这里的任何帮助将不胜感激。

最佳答案

首先,请确保import base64。然后,尝试以二进制模式读取文件。特别,
with open(os.path.join(path, i), 'rb') as attachment:
然后,您可以读取文件的内容,在base64中对其进行编码,然后将其设置为零件的有效负载,例如:
part.set_payload(base64.b64encode(attachment.read()))
当然,删除下一​​行(encoders.encode_base64(part)),无论如何我都认为encoders已被弃用。

我相信这应该可以解决问题。

关于python-3.x - 电子邮件未发送excel附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60652485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com