How to send a file as an attachment by email without it being automatically renamed?
I am new to sending emails via script and I 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 file.jpg appears as ATT0001 in the email. Renamed and without the extension .jpg he has. The same goes for text and audio files. How do I make the files keep their name and extension when they are sent as attachments?
1 answers
You are not setting the attachment name, so a generated name is being used. Try swapping the line:
mime=MIMEImage(f.read(),subtype='jpg')
By:
mime=MIMEImage(f.read(),subtype='jpg', name=os.path.basename(path))
Naturally, 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 content header before calling enviaremail
:
msg.add_header('Content-Disposition', 'attachment', filename='foto.jpg')
See this example in the documentation.
Edition
Here's a small example code that does just that: reads an image from 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()
Result: