Задать вопрос
Этот вопрос закрыт для ответов, так как повторяет вопрос Charmap' codec can't decode byte 0x98 in position 169: character maps to?
@Foxford12

'charmap' codec can't decode byte 0x98 in position 169: character maps to?

Файл 1.txt лежит в папке attachments. Почему не работает код?

import smtplib
import os
import time
import mimetypes
from pyfiglet import Figlet
from tqdm import tqdm
from email import encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase



def send_email(text=None, template=None):
    sender = "Почта"
    # your password = "your password"
    password = "Пароль"

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()

    try:
        with open(template, encoding="UTF-8") as file:
            template = file.read()
    except IOError:
        template = None


        server.login(sender, password)
        msg = MIMEMultipart()
        msg["From"] = sender
        msg["To"] = sender
        msg["Subject"] = "У вас новый посититель"

        if text:
            msg.attach(MIMEText(text))

        if template:
            msg.attach(MIMEText(template, "html"))

        print("Collecting...")
        for file in tqdm(os.listdir("attachments")):
            time.sleep(0.4)
            filename = os.path.basename(file)
            ftype, encoding = mimetypes.guess_type(file)
            file_type, subtype = ftype.split("/")

            if file_type == "text":
                with open(f"attachments/{file}") as f:
                    file = MIMEText(f.read())
            elif file_type == "image":
                with open(f"attachments/{file}", "rb") as f:
                    file = MIMEImage(f.read(), subtype)
            elif file_type == "audio":
                with open(f"attachments/{file}", "rb") as f:
                    file = MIMEAudio(f.read(), subtype)
            elif file_type == "application":
                with open(f"attachments/{file}", "rb") as f:
                    file = MIMEApplication(f.read(), subtype)
            else:
                with open(f"attachments/{file}", "rb") as f:
                    file = MIMEBase(file_type, subtype)
                    file.set_payload(f.read())
                    encoders.encode_base64(file)

            # with open(f"attachments/{file}", "rb") as f:
            #     file = MIMEBase(file_type, subtype)
            #     file.set_payload(f.read())
            #     encoders.encode_base64(file)

            file.add_header('content-disposition', 'attachment', filename=filename)
            msg.attach(file)

        print("Sending...")
        server.sendmail(sender, sender, msg.as_string())




def main():
    font_text = Figlet(font="slant")
   # print(font_text.renderText("SEND EMAIL"))
    text = "Hello"
    template = "1.txt"
    print(send_email(text=text, template=template))


if __name__ == "__main__":
    main()

Вот ошибка:

Collecting...
 67%|██████▋   | 2/3 [00:01<00:00,  1.31it/s]
Traceback (most recent call last):
  File "D:\Глазок онлайн\main.py", line 26, in send_email
    with open(template, encoding="UTF-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: '1.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 92, in <module>
    main()
  File "", line 88, in main
    print(send_email(text=text, template=template))
  File "", line 53, in send_email
    file = MIMEText(f.read())
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\encodings\cp1251.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 169: character maps to <undefined>

Process finished with exit code 1
  • Вопрос задан
  • 180 просмотров
Подписаться 1 Простой 4 комментария
Ваш ответ на вопрос

Вопрос закрыт для ответов и комментариев

Потому что уже есть похожий вопрос.
Похожие вопросы