How do I send a file as an attachment by email without automatically renaming it?

Asked

Viewed 3,590 times

3

I am beginner in sending emails via script and am facing a problem. I use Python 3.5. When sending attachments with the following script, they lose the extension and are renamed:

def enviaremail(usuario,senha,mensagem,listadestinatarios):
    from smtplib import SMTP
    smtp=SMTP('smtp.live.com',587)
    smtp.starttls()
    smtp.login(usuario,senha)
    smtp.sendmail(usuario,listadestinatarios,mensagem)
    smtp.quit()
    print('E-mail enviado com sucesso')
def anexoimagem(path):
    from email.mime.image import MIMEImage
    with open(path,'rb') as f:
        mime=MIMEImage(f.read(),subtype='jpg')
    return mime
msg=anexoimagem('foto.jpg')
msg['From']='[email protected]'
msg['To']='[email protected]'
msg['Subject']='testando mensagem com anexo'
enviaremail('[email protected]','xxxx',msg.as_string,['[email protected]']

For example, the photo.jpg file appears as ATT0001 in the email. Renamed and without the . jpg extension it has. The same is true for text and audio files. How do I keep your name and extension when sending as attachments?

1 answer

6


You are not setting the name of the attachment, so a generated name is being used. Try changing the line:

mime=MIMEImage(f.read(),subtype='jpg')

for:

mime=MIMEImage(f.read(),subtype='jpg', name=os.path.basename(path))

Of course, to use the function basename you will need to import the package os:

import os

You can also indicate the file name in the MIME header before the call enviaremail:

msg.add_header('Content-Disposition', 'attachment', filename='foto.jpg')

Behold that example in the documentation.

Editing

Here’s a small example code that does just that: reads an image of the file with the name "img.jpg" and sends it in the email as if its name were "Ó o auê aí, ô.jpg":

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

smtp_server = '<seu servidor aqui>'
smtp_port = <porta>
acc_addr = '<seu email aqui>'
acc_pwd = '<sua senha aqui>'

to_addr = '<seu destinatário aqui>'
subject = 'Teste do SOPT!'
body = 'Este é um teste de envio de email via Python!'

# Configura o servidor de envio (SMTP)
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(acc_addr, acc_pwd)

# Cria o documento com várias partes
msg = MIMEMultipart()
msg["From"] = acc_addr
msg["To"] = to_addr
msg["Subject"] = subject

# Anexa a imagem
imgFilename = 'Ó o auê aí, ô.jpg' # Repare que é diferente do nome do arquivo local!
with open('img.jpg', 'rb') as f:
    msgImg = MIMEImage(f.read(), name=imgFilename)
msg.attach(msgImg)

# Anexa o corpo do texto
msgText = MIMEText('<b>{}</b><br><img src="cid:{}"><br>'.format(body, imgFilename), 'html')
msg.attach(msgText)

# Envia!
server.sendmail(acc_addr, to_addr, msg.as_string())
server.quit()

Upshot:

inserir a descrição da imagem aqui

  • I wanted something related to your first suggestion, but it was a mistake. I said that the "name" argument does not exist in init from Mimeimage. Maybe you don’t have something like this that works, @?

  • Well, I just tested it here (again) and it worked. And my version is also 3.5. There must be something wrong with your code. I will edit the answer and add the test code I used.

  • 1

    I tried your second tip and it worked. Even the first one didn’t work for me, it should work for others, since it worked on your script. Anyway, thank you. The second tip solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.