@stulevtoday
Дурак, глупо, но самокритично.

Почему не удаётся отправить письмо со вложением на почту через SMTP?

Сам код:
def post_mail():
    import smtplib

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

    filepaths = ['drom/export/kms.xlsx', 'drom/export/delivery.xlsx']
    for i, recipient in enumerate(drom_mails):
        filepath = filepaths[i]
        subject = 'AllMyParts'
        text = ''
        html = '<html><head></head><body>' + text + '</body></html>'

        basename = os.path.basename(filepath)
        filesize = os.path.getsize(filepath)

        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = 'Python script <' + user + '>'
        msg['To'] = ', '.join(recipient)
        msg['Reply-To'] = user
        msg['Return-Path'] = user

        part_text = MIMEText(text, 'plain')
        part_html = MIMEText(html, 'html')
        part_file = MIMEBase('application', 'octet-stream; name="{}"'.format(basename))
        part_file.set_payload(open(filepath, "rb").read())
        part_file.add_header('Content-Description', basename)
        part_file.add_header('Content-Disposition', 'attachment; filename="{}"; size={}'.format(basename, filesize))
        encoders.encode_base64(part_file)

        msg.attach(part_text)
        msg.attach(part_html)
        msg.attach(part_file)

        mail = smtplib.SMTP_SSL(server2)
        mail.login(user, password)
        mail.sendmail(user, recipient, msg.as_string())
        mail.quit()

Ошибка:

Traceback (most recent call last):
File "C:\Users\PycharmProjects\xl\drom\main.py", line 236, in
post_mail()
File "C:\Users\PycharmProjects\xl\drom\main.py", line 229, in post_mail
mail.sendmail(user, recipient, msg.as_string())
File "C:\Users\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 892, in sendmail
raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (550, b'your mailer sends invalid headers')

Также за 1 час отыскал второй код:
def post_mail():
    import smtplib
    import mimetypes
    from email import encoders
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    filepaths = ['drom/export/kms.xlsx', 'drom/export/delivery.xlsx']
    for i, recipient in enumerate(drom_mails):
        mail = smtplib.SMTP(server2, 465)
        print(filepaths[i])

        mail.login(user, password)
        msg = MIMEMultipart()
        msg["From"] = user
        msg["To"] = recipient
        msg["Subject"] = "AllMyParts"

        print("Collecting...")
        filename = os.path.basename(filepaths[i])
        ftype, encoding = mimetypes.guess_type(filepaths[i])
        file_type, subtype = ftype.split("/")

        with open(filepaths[i], "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...")
        mail.sendmail(user, recipient, msg.as_string())
        mail.quit()

Но на нём я вообще не могу подключиться к почте.
  • Вопрос задан
  • 468 просмотров
Пригласить эксперта
Ответы на вопрос 2
dimonchik2013
@dimonchik2013
non progredi est regredi
Ответ написан
Комментировать
noook
@noook
python and fishing
1) Посмотрите три видео
https://www.youtube.com/watch?v=ZvAGL0EDLVY
https://www.youtube.com/watch?v=VniC5LAOYjY
https://www.youtube.com/watch?v=ozSPlNDar3A
2) надо бы хорошо знать возможности (параметры) сервера с помощью которого будете отправлять письма
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы