电子邮件未发送excel附件

问题描述 投票:0回答:1

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

csv看起来像这样

Name,Emails,Firm
Tom,[email protected],Firm1
Dick,[email protected],Firm2
Harry,[email protected],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 = "[email protected]"
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>

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

python-3.x email error-handling email-attachments python-unicode
1个回答
0
投票
with open(os.path.join(path, i), 'rb') as attachment:

然后,您可以读取文件的内容,在base64中对其进行编码,然后将其设置为零件的有效载荷,例如:

part.set_payload(base64.b64encode(attachment.read()))

当然删除下一行(encoders.encode_base64(part)),我认为encoders仍然被弃用。

我相信这可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.