0

I'm sending an e-mail through smtplib in Python with a xlsx file in attachment. I can open the attachment in Gmail website, but in Thunderbird the file doesn't appear.

I need to use Thunderbird because it is the preferred tool to the client that I'm working for.

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


def enviar_email(email):
    smtp_server = 'smtp.gmail.com'
    port = 465
    sender = 'proex.crim@gmail.com'
    password = '**********'
    receiver = email
    context = ssl.create_default_context()
    message = MIMEMultipart('alternative')
    message['Subject'] = 'Pesquisa finalizada'
    message['From'] = sender
    message['To'] = receiver
    filename = f'C:\\Users\\evand\\OneDrive\\Desktop\\projeto\\core\\funcoes\\{email}.xlsx'



    with open(filename, 'rb') as attachment:
        part_a = MIMEBase('application', 'octet-stram')
        part_a.set_payload(attachment.read())
        filename = 'Resultado da Pesquisa.xlsx'

    encoders.encode_base64(part_a)

    text = f"""\
        Olá, segue em anexo o resultado da pesquisa solicitada no nosso site. 
        Enviamos para você um arquivo com os processos correspondentes aos CNPJs pesquisados.
    
    
    """

    html = """\
        <html>
            <body>
            <p> Olá, segue em anexo o resultado da pesquisa solicitada no nosso site. <br>
            </p>
            <p> Enviamos para você um arquivo com os processos correspondentes aos CNPJs pesquisados.</p>
        </body>
    </html>
    
    """

    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')

    part_a.add_header(
        'Content-Disposition',
        f'attachment; filename= {filename}',
    )

    message.attach(part1)
    message.attach(part2)
    message.attach(part_a)

    context = ssl.create_default_context()

    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        server.login(sender, password)
        server.sendmail(sender, receiver, message.as_string())

enter image description here

enter image description here

MattDMo
  • 90,104
  • 20
  • 213
  • 210
  • 1
    I'm in no way an expert but multipart/alternative should be the "mail" part only, IMHO. https://stackoverflow.com/questions/3902455/mail-multipart-alternative-vs-multipart-mixed/28833772 – mansuetus Oct 15 '20 at 13:50
  • 1
    Thank you very much, I'm not an expert too, I started to work with that this year, and you solve my problem. I just changed multipart/alternative to multipart/mixed. – Evandro Lippert Oct 15 '20 at 14:11
  • 1
    glad I could help : I was puzzled when Thunderbird did not work, it _had_ to be "your fault" :-p – mansuetus Oct 15 '20 at 17:19

0 Answers0